The Wayback Machine - https://web.archive.org/web/20240710094733/https://www.geeksforgeeks.org/recursion-in-ruby/
Open In App

Recursion in Ruby

Last Updated : 10 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
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.



Previous Article
Next Article

Similar Reads

Difference between Ruby and Ruby on Rails
1. Ruby : Ruby is an object-oriented scripting language launched in 1995 and is known as a general-purpose programming language. It was programmed in C programming language. Ruby is a secured programming language and its syntax is similar to Perl and Python. It was developed on the principle of user interface design and it is mainly used to develop
3 min read
Private Classes in Ruby
The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private cons
3 min read
Ruby | Matrix cofactor() function
The cofactor() is an inbuilt method in Ruby returns the cofactor of the given index. Syntax: mat1.cofactor(i, j) Parameters: The function needs two index i and j, whose cofactor is to be returned. Return Value: It returns the cofactor of the given index. Example 1: # Ruby program for cofactor() method in Matrix # Include matrix require &quot;matrix
1 min read
Ruby Integer odd? function with example
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number.odd? Parameter: The function takes the integer which is to be checked for odd or not. Return Value: The function returns a boolean value which determines if the value is odd or not. Example #1: # Ruby program of integer odd
1 min read
Ruby Integer div() function with example
The div() function in Ruby returns the integer division of two numbers. Syntax: (number1).div(number2) Parameter: The function needs two numbers number1 and number2, where number1 is the dividend and number2 is the divisor. Return Value: The function returns the integer division of two numbers. Example #1: # Ruby program of Integer div() function #
1 min read
Ruby | Symbol to_s function
Symbol#to_s() : to_s() is a Symbol class method which returns string representation of the symbol object. Syntax: Symbol.to_s() Parameter: Symbol values Return: string representation of the symbol object. Example #1 : # Ruby code for Symbol.to_s() method # declaring Symbol a = :aBcDeF # declaring Symbol b = :&quot;\u{e4 f6 fc}&quot; # declaring Sym
1 min read
Ruby | Set replace() function
The replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self. Syntax: s1.replace(enum) Parameters: The function accepts an enumerable object which to be replaced in the set. Return Value: It returns the self object which contains the contents of the set after rep
1 min read
Ruby | Set reset() function
The reset() is an inbuilt method in Ruby resets the internal state after modification to existing elements and returns self. The elements will be reindexed and deduplicated. Syntax: s1.reset() Parameters: The function does not accepts any parameter. Return Value: It returns self . Example 1: # Ruby program to illustrate # the reset() method # requi
1 min read
Ruby | Array Concatenation using (+) function
Array#+() is a Array class method which performs set concatenate operation arrays by combining two arrays to a third array. Syntax: Array.+() Parameter: Arrays for performing the concatenation operation. Return: New arrays by combining two arrays. Example #1 : # Ruby code for +() method # showing concatenate operation # declaring array a = [18, 22,
2 min read
Ruby | at() function
The at() function in Ruby is used to return the element of the specified index. Index 0 is for the first element of the array, 1 for the second element of the array and so on. The negative index counts from the end of the input array. Syntax: Array.at(Index) Here Array is the input array of elements at which at() function is called. Parameters: Ind
2 min read
three90RightbarBannerImg