How to Calculate Factorial in Ruby Recursively
Q: Implement a Ruby program that calculates the factorial of a given number using recursion.
- Ruby
- Mid level question
Explore all the latest Ruby interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Ruby interview for FREE!
Certainly! Here's an example of a Ruby program that calculates the factorial of a given number using recursion:
def factorial(n) if n == 0 1 else n * factorial(n - 1) end end # Example usage: number = 5 result = factorial(number) puts "The factorial of #{number} is: #{result}"
In this program, we define a method factorial that takes a number n as input. Inside the method, we have a base case when n is equal to 0, in which case we return 1 since the factorial of 0 is defined as 1.
If n is not 0, we recursively call the factorial method with n - 1 and multiply it by n. This recursive calculation continues until we reach the base case.
In the example usage, we provide the input number 5 and assign the result of the factorial calculation to the variable result. Then, we simply print the result using string interpolation, which outputs "The factorial of 5 is: 120" to the console.
You can replace the value of the number variable with any non-negative integer for which you want to calculate the factorial.


