I have a method called fibs_rec that results in an unexpected output:
def fibs_rec(n)
if n == 1 || n == 0
return 1
else
a = fibs_rec(n-1) + fibs_rec(n-2)
puts a
return a
end
end
fibs_rec(5)
The call fibs_rec(5) should return 1,1,2,3,5 but here is the actual output:
2
3
2
5
2
3
8
Not only is the output incorrect, it lacks a number from the beginning.
Can someone explain why is this happening?
1,1,2,3,5seems like multiple values. You could return the values as an array, i.e.[1,1,2,3,5]. Or – a bit more idiomatic – you couldyieldeach value to a block. (maybe returning an enumerator if no block is given)putsonly if n > 1, and only for the case n <= 1, fib_rec would return a 1. Hence you never see a 1 in your output. Also, your question is unclear: You are asking about the output of the function, which is whatputsis taken care, but then are also mention return a value. Outputting something and returning a value are two different, unrelated things, so please make clear in your posting what you exactly want.