cresjoy - 11 months ago 53

Ruby Question

Here are two versions of fibonacci I thought of

`def fibonacci( n )`

return n if ( 0..1 ).include? n

( fibonacci( n - 1 ) + fibonacci( n - 2 ) )

end

puts fibonacci( 5 )

def fib(n)

if n == (0..1)

return n

elsif

return fib(n-1) + fib(n-2)

end

end

puts fib(5)

Why doesent the second fib(n) work?

Answer

It is because `n == (0..1)`

is never satisfied if `n`

is a number. The range `0..1`

is not a number. A minimum fix is:

```
(0..1) === n
```

Source (Stackoverflow)