6

ruby で階乗への最初のアプローチ (無限ループ) が機能しないのに、2 番目のアプローチが機能するのはなぜだろうか。

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
4

1 に答える 1

7

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.

于 2012-05-26T07:42:21.093 に答える