1

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?

Muntasir Alam
  • 1,777
  • 2
  • 17
  • 26

2 Answers2

2

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
sawa
  • 165,429
  • 45
  • 277
  • 381
2

You need to remove the elsif in favor of else (since you have no case), and also reverse the ===

def fib(n)
  if (0..1) === n
    return n
  else
    return fib(n-1) + fib(n-2)
  end
end
puts fib(5)
danielrsmith
  • 4,050
  • 3
  • 26
  • 32
  • There is no "the" `===`. – sawa Jun 27 '16 at 15:41
  • Why does === need to be the other way around? Why does double equal not work? – Muntasir Alam Jun 27 '16 at 15:43
  • `a === b` is just syntactic sugar for `a.===(b)`. So the object `a` is having the `===` method run. A number's `===` method is an equality comparison. On the other hand `(0..1)` is a `Range` object, and it's `===` method is a "include" type operation: http://ruby-doc.org/core-2.2.0/Range.html#method-i-3D-3D-3D . `==` won't work because as the documentations states, it needs to be the exact same range. – danielrsmith Jun 27 '16 at 15:48
  • @cresjoy you should accept sawa's answer it was correct. – danielrsmith Jun 27 '16 at 15:52
  • May I ask why, when I did n == (0..1), it gave me a stack overflow error? I know this is syntatically wrong. But that error gives the impression of infinite recursion. – Muntasir Alam Jun 27 '16 at 15:59
  • 1
    Since `n == (0..1)` never evaluated to true, you had no condition to stop the recursion. – danielrsmith Jun 27 '16 at 16:00