find the factorial of a number in ruby

To find the factorial of a number in Ruby, we can use a loop to multiply the number by each decreasing integer until we reach 1. Here's an example function that takes a number as input and returns its factorial:

main.rb
def factorial(num)
  result = 1
  while num > 0
    result *= num
    num -= 1
  end
  return result
end
105 chars
9 lines

We initialize a result variable to 1, then use a while loop to repeatedly multiply it by num and decrement num by 1 until num reaches 1 or below. Finally, we return the result.

We can call this function to find the factorial of a number like this:

main.rb
puts factorial(5) # prints 120
31 chars
2 lines

This will output the factorial of 5, which is 120.

related categories

gistlibby LogSnag