Toyi Hill Toyi Hill - 1 year ago 80
Ruby Question

How this Fibonacci code(Ruby) works?

I understood how the formula for Fibonacci works but not the recursion part.
For example, fib(4) will call for fib(3) + fib(2), then what? How does the method determines the value of fib(3) and fib(2)? I am a beginner in Ruby so please excuse me for asking a noob question.

def fib num
return num if(0..1).include? num
fib(num-1) + fib(num-2)

Answer Source

Recursion works by calling itself again and again until the 'break point' happens. Fib(4) calls for fib(3) and fib(2), fib(3) calls for fib(2) and fib(1)... method has given the value of fib(1) and fib(0) as 1.

Let me try to explain it visually:

> fib(4) =         fib(3)                 +            fib(2) 
> =>       fib(2)        +   fib(1)       +        fib(1)  +  fib(0)
> =>   fib(1) + fib(0)   +   1            +          1     +   1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download