I wonder why the first approach to factorial does not work (infinite loop) in ruby while the second does.
def fac (x)
if x == 0
return 1
else
return (fac (x-1) * x)
end
end
def fact( num )
return 1 if num == 0
fact(num - 1) * num
end
The difference is the space after the method name, not the way you structured your if-else.
fac (x-1) * x
is parsed as fac((x-1) * x)
. Basically if a method name is followed by a space (or any token that is not an opening parenthesis), ruby assumes you're calling the method without parentheses. So it interprets the parentheses around x-1
as grouping, not a part of the method call syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With