There are a number of problems with your method:
def find_fib(anumber)
return anumber if anumber <= 1
(find_fib(anumber - 1) + find_fib(anumber - 2)) # 1
# ETC...
@fib.push(number) # 2 and 3
end
You're calculating a Fibonacci number here, but you don't assign the value to a variable, so you're basically throwing away the number.
The last statement evaluated in a Ruby function gets returned, unless you make an explicit
return
statement like in your first line. As Arie Shaw points out, that last line returns an array object, while the first line returns a number, so you're trying to callArray + Fixnum
, which is not a defined operation.You're pushing
number
into your@fib
array, but that variable isn't assigned a
value anywhere.
If you want a method that generates an array of the first n
Fibonacci numbers, here's one Ruby way to do it:
def fib(n)
(n == 1) ? [0] : (2..(n-1)).each_with_object([0,1]) { |i,a| a[i] = a[i-2] + a[i-1] }
end