I am getting the "undefined method '+'" eror on line 11. Not sure why.
#Make an array of Fibonacci numbers till 4 million
r=2
i=1
fibo=[1]
s=0
t=0
for r in 1..4000000
r=fibo[i]
t=fibo[i-1]
s=r+t
r+=s
i+=1
end
puts fibo
In your assign fibo=[1] that means fibo[0] = 1 but what is the value of fibo[1] ?
fibo[1] will be nill
r=fibo[i] # r = 1
t=fibo[i-1] # t = nil
s=r+t # will show undefined method for nill
To fix your issue, assign
fibo[1] = 1
The error was fixed by reversing how I wrote the assignment operator. Instead of
r=fibo[i]
t=fibo[i-1]
s=r+t
I did
fibo[i]=r
fibo[i-1]=t
s=r+t
This is because since the code is read right to left, the fibo[i] parts (which were nil) were being assigned to the variables. The variables then could not be operated on.
Once the initialized variables were instead first assigned to the array indices, the array indices were not nil, and the variables themselves could be operated on.
i,fibo[i]doesn't exist.fibo, it's always anArraythat has one element.for r in 1..4000000and givera new value immediately in the iteration? My suggestion is: learn how to debug, not necessarily an advanced debugger, just starts with usingputsandpto output values of variables and debug.forloop. ruby haseachand others