0

I am trying to write a simple custom function for fibonacci, But i am getting a error:

My code :

class Fibonacci
 def fib(num)
  @num = num.to_i
  series = Array.new
  series[0] = 0
  series[1] = 1

  for i in 0..series[@num]
    series[@num+2] = series[@num] + series[@num+1]
  end
  return series
 end
end

obj = Fibonacci.new
obj.fib(8)

Error :

ruby fibonacci.rb
fibonacci.rb:9:in `fib': bad value for range (ArgumentError)
from fibonacci.rb:19:in `<main>'
2
  • Sidenotes: to_i and return are unnecessary here; series = [0,1] can replace lines 2 to 4 in your method definition; use two spaces for indentation throughout; for is not idiomatic Ruby. Commented Mar 21, 2017 at 3:54
  • sure @sagarpandya82, will refactor it. Commented Mar 21, 2017 at 4:07

1 Answer 1

2

You're getting ArgumentError from 0..series[@num], where series[@num] will be nil at that point.

I think you meant to have:

for i in 0..@num
  series[i+2] = series[i] + series[i+1]
end
Sign up to request clarification or add additional context in comments.

1 Comment

To avoid the 2 extra items, you could change the loop to 2.upto(@num) { |i| series[i] = series[i-2] + series[i-1] }

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.