Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby recursion issue

Tags:

ruby

recursion

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
like image 840
AlexLiesenfeld Avatar asked May 26 '12 07:05

AlexLiesenfeld


1 Answers

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.

like image 189
sepp2k Avatar answered Sep 22 '22 16:09

sepp2k