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 would do
(1..n).inject(1, :*)
Here is my version seems to be clear to me even though it's not as clean.
def factorial(num)
step = 0
(num - 1).times do (step += 1 ;num *= step) end
return num
end
This was my irb testing line that showed each step.
num = 8;step = 0;(num - 1).times do (step += 1 ;num *= step; puts num) end;num
There is no factorial function in the standard library.
Like this is better
(1..n).inject(:*) || 1
You could also use Math.gamma function which boils down to factorial for integer parameters.
And yet another way (=
def factorial(number)
number = number.to_i
number_range = (number).downto(1).to_a
factorial = number_range.inject(:*)
puts "The factorial of #{number} is #{factorial}"
end
factorial(#number)