Open In App

Recursion in Ruby

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Recursion makes the process easier and it reduces a lot of compiling time. In Ruby, we can put all the actions in a loop, so that they can be repeated several times. So why is there a need for Recursion?

Since in Ruby, we introduce real-life variables, Recursion plays a vital role in solving major real-life problems in Ruby. 

Iterative Code

We can understand the steps while considering the very simple problem of summing the array. Writing an iterative code would mean running a loop through the array adding each element to a variable and then returning the variable.

Example:

Ruby
# Iterative program to sum a given array of numbers.
def iterativeSum(arrayofNumbers)
  sum = 0
  arrayofNumbers.each do |number|
    sum += number
  end
  sum
end

# Calling the method and printing the result:
puts iterativeSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# This code is modified by Rushik Ghuntala

Output
55

Recursive Code

In this code, the method calls itself. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems.

Example: 

Ruby
# Recursive method to calculate the sum of all numbers in a given array.
def RecursiveSum(arrayofNumbers)
  # Base Case: If the array is empty, return 0.
  return 0 if arrayofNumbers.empty?

  # Recursive code: Adding each element to the variable by calling the method.
  sum = arrayofNumbers.pop 
  return sum + RecursiveSum(arrayofNumbers)
end

puts RecursiveSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Output
55

The concept of how the Recursive steps are carried on can be understood using yet another example. In the following example, we would execute a simple program of finding the Factorial of a given number
The code for the above-mentioned program is as follows: 

Example : 

Ruby
# Ruby code for calculating the 
# factorial of a number recursively.
def RecursiveFactorial(number)

# Base Case:
  if (0..1).include?(number)
    return 1
  end

#Recursive call: 
    return number * RecursiveFactorial(number - 1)
end
# Calling the method:
puts RecursiveFactorial(6)

# This code is modified by Susobhan Akhuli

Output
720

Explanation:

The method for calculating the factorial of 6 is called first which further calls the one to calculate for 5 then for 4 until it reaches a point where RecursiveFactorial(1) is called which returns 1 as the answer. Here the recursion calls work as they multiply each call’s result with the already existing answer. The same can be shown in the following steps: 

RecursiveFactorial(6) = 6 * RecursiveFactorial(5) 
= 6 * 5 * RecursiveFactorial(4) 
= 6 * 5 * 4 * RecursiveFactorial(3) 
= 6 * 5 * 4 * 3 * RecursiveFactorial(2) 
= 6 * 5 * 4 * 3 * 2 * RecursiveFactorial(1) 
= 6 * 5 * 4 * 3 * 2 * 1 
= 720 

Recursive Code Example: Fibonacci Number Calculation

Another example of recursion is calculating the Nth Fibonacci number. The base case is when ‘N‘ is less than 2, where the Fibonacci number is ‘N‘ itself. The recursive call involves summing the results of ‘(n-1)th’ and ‘(n-2)nd’ Fibonacci numbers.

Example: 

Ruby
def recursiveFibonacci(n)
  return n if n < 2
  recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2)
end

puts recursiveFibonacci(3)

Output
2

Benefits and Limitations of Recursion

Recursion simplifies solving problems by breaking them into smaller, more manageable sub-problems, often leading to cleaner and more readable code. However, recursion in Ruby can sometimes result in a SystemStackError: stack level too deep when handling large inputs. This limitation necessitates using iterative approaches for problems with large input sizes.

By mastering recursion, one can solve numerous problems more efficiently and with fewer lines of code. While iterative methods are often more suitable for large-scale problems due to system limitations, recursion remains a powerful tool in a programmer’s arsenal.



Next Article

Similar Reads