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.rb105 chars9 linesWe 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.rb31 chars2 lines
This will output the factorial of 5, which is 120.
gistlibby LogSnag