Question

def fib(n)
  [0,1].include? n ? n : (fib(n-1) + fib(n-2))
end

fib 5 => false

Why is this? Since it works when broken out into standard if then else.

Was it helpful?

Solution

Operator precedence. You're effectively doing this:

[0, 1].include? (n ? n : fib...)

That is, the result of n ? n : (fib(n-1) + fib(n-2)) is found, and that is passed to include?.

Use parenthesis to force the order of evaluation you intend:

[0, 1].include?(n) ? n : (f(n - 1) + fib(n - 2))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top