views:

660

answers:

2

I'm going crazy: Where is the Ruby function for factorial? No, I don't need tutorial implementations, I just want the function from the library. It's not in Math!

I'm starting to doubt, is it a standard library function?

+8  A: 

There is no factorial function in the standard library.

sepp2k
+6  A: 

It's not in the standard library but you can extend the Integer class.

class Integer
  def factorial_recursive
    self <= 1 ? 1 : self * (self - 1).factorial
  end
  def factorial_iterative
    f = 1; for i in 1..self; f *= i; end; f
  end
  alias :factorial, :factorial_recursive
end

N.B. Iterative factorial is a better choice for obvious performance reasons.

Pierre-Antoine LaFayette
He explicitly said, he doesn't want an implementation.
sepp2k
He may not; but people searching SO for "Ruby factorial" might.
Pierre-Antoine LaFayette
another implementation here: http://rosettacode.org/wiki/Factorial#Ruby
glenn jackman
That is an elegant way to do it :)
Pierre-Antoine LaFayette