I am writing a method that returns the nth element in the Fibonacci sequence, but am running into an unexpected end error.
def fib_seq(n)
a = [0]
n.times do |i|
if i==0
a[i] = 0
else if i==1
a[i] = 1
else
a[i] = a[i-1] + a[i-2]
end
end
return a[n]
end
puts fib_seq(4)
Any tip on what I can be screwing up on?
Assuming you are trying to return the nth (and not the (n-1)th, i.e. fib(1) = 0 NOT fib(0) = 0).
I fixed it by changing:
to
(AND)
to
So your final code should look like:
Per your comment below, the following code will work:
If you want to output the fibs as a list then use:
Instead of