0

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
6
  • Because for some i, fibo[i] doesn't exist. Commented Jun 24, 2015 at 7:02
  • 1
    You never modified fibo, it's always an Array that has one element. Commented Jun 24, 2015 at 7:02
  • Also, why are you using for r in 1..4000000 and give r a new value immediately in the iteration? My suggestion is: learn how to debug, not necessarily an advanced debugger, just starts with using puts and p to output values of variables and debug. Commented Jun 24, 2015 at 7:04
  • Also dont use for loop. ruby has each and others Commented Jun 24, 2015 at 7:05
  • What is your question? Commented Jun 24, 2015 at 8:15

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

These are the changes I made: fibo = [] fibo[0]=1 fibo[1]= 2 ..... r=fibo[i] t=fibo[i-1] s=r+t r+=s i+=1 end I still get the same error.
0

In your case fibo has only one element in array. you are trying to get element from index 1(i). which is causing error

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.