Home »
Ruby Tutorial »
Ruby Programs
Ruby program to calculate the factorial of given number using recursion
Last Updated : December 15, 2025
Problem Solution
In this program, we will create a recursive function to calculate the factorial of a specified number and return the result.
Program/Source Code
The source code to calculate the factorial of a given number using recursion is given below. The given program is compiled and executed successfully.
# Ruby program to calculate the factorial
# using the recursion
def factorial(num)
if num == 1
return 1;
else
return num * factorial(num-1);
end
end
print "Enter number: ";
num = gets.chomp.to_i;
fact = factorial(num);
print "Factorial is: ",fact;
Output
Enter number: 5
Factorial is: 120
Explanation
In the above program, we created a recursive function factorial(). Here, we read an integer number from the user and passed it to the factorial() function and got the factorial of a specified number and printed the result.
Ruby User-defined Functions Programs »
Advertisement
Advertisement