Understanding, Recursion in Ruby -
in recursion, method calls itself. i'm not following when there return values. example, in "learn program" book chris pine, there example on factorials.
def factorial num if num < 0 return 'you cant\'t take factorial of negative number!' end if num <= 1 1 else num * factorial(num-1) end end
if call method factorial(3)
, go else
portion of code , this:
3 * factorial(3-1)
and should return 6
since 3*2=6
. factorial(3-1)
calls factorial
method passing 2
within recursion. num = 2
, , 2 * factorial(2-1)
, 2*1=2
.
what happens 6
got our first run through code? num = 1
, looks return 1
, go end of code. understanding, still have 6
, 2
previous recursions. correct in assumption, since called factorial function when multiplied num
? can me understand better? called factorial(10)
, how work out?
first, should replace return 'blabla'
raise 'blabla'
because function returns numeric, not string.
then see this
factorial(3) 3 * factorial(2) 2 * factorial(1) 1 # no more recursion, let's go replacing # function calls returned value end end end # ↓ factorial(3) 3 * factorial(2) 2 * 1 # let's go again ! end end # ↓ factorial(3) 3 * 2 # end # ↓ 6
Comments
Post a Comment