+ 1

Help plis.

def fact (n) if n <=1 1 else n*fact (n-1) end end. here in second line if n <=1. what code is run when the if statement is true...

30th Jan 2017, 6:41 AM
stephen haokip
stephen haokip - avatar
1 Resposta
0
The last thing evaluated in a method gets returned to wherever the method was called from. Because there is nothing after the if...else...end, the value 1 is returned from the fact method when the n <= 1 is true. You can think of this: def fact(n) if n <=1 1 #last line of fact when n <= 1 else n * fact(n-1) #last line when n > 1 end end the same as you would think of this: def fact(n) if n <=1 return 1 else return n * fact(n-1) end end So if the n <= 1 is true, it will return 1 to wherever the fact method was called from. This could be a puts statement like: puts fact(1) where the "fact(1)" becomes the returned value 1, or it could return to the fact method call from within the else section of a previous fact method call: n * fact(n - 1) #same as fact(1) if n is 2 and this is the hardest part to understand about recursion. Hope this answers your original question!
16th Feb 2017, 7:22 PM
Brad
Brad - avatar