+5

Recursion in Ruby

Can anyone explain this code please? def fib(num) if num < 2 num else fib(num-1) + fib (num - 2) end end puts fib(4)

3/8/2019 10:53:22 AM

Isaac Jesudamilare

4 Answers

New Answer

+49

It does the operation from right to left.  3 = (2-1) + (4-2)       ⬅️ ⬅️ ⬅️ That's why the result is 3

+7

Because you have marked 4 for "num" variable, if 4 is not less than 2, so, Ruby go to add the 2 methods (num - 1) and (num + 2).

+6

// He's printing "3" : https://code.sololearn.com/cfgSVqQD22G3/?ref=app

+1

You ruby Program are compute the fibonacci number of the giv'n number. Please look at wikipedia for more informations