Ruby factorial function Ruby factorial function ruby ruby

Ruby factorial function


There is no factorial function in the standard library.


Like this is better

(1..n).inject(:*) || 1


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_iterativeend

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