Ruby recursion problem

I wonder why the first approach to factorial does not work (an endless loop) in ruby, and 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 
+6
source share
1 answer

The difference is a space after the method name, not a way to structure your if-else.

fac (x-1) * x parsed as fac((x-1) * x) . Basically, if the name of the method is followed by a space (or any token that is not an opening bracket), ruby ​​assumes that you are calling the method without parentheses. Therefore, it interprets the parentheses around x-1 as a grouping, and not part of the syntax of a method call.

+7
source

Source: https://habr.com/ru/post/916730/


All Articles