The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Recursion makes the process easier and it definitely reduces a lot of compiling time. In Ruby, we do have an option of putting all the actions in a loop, so that they could be repeated a given number of times. So why is there a need for Recursion?
Since in Ruby, we introduce real life variables, Recursion plays a very important role in solving major real life problems in Ruby.
We can understand the steps while considering a very simple problem of summing the array. Writing an iterative code would mean running a loop through the array and add each element to a variable and then returning the variable.
Writing the 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.
The concept of how actually the Recursive steps are carried on can be understood using a 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:
The code works as follows:
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 works as it multiplies the result of each call with the already existing answer. The same can be shown as 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
Another example is a code for calculating the Nth Fibonacci number. Here the base case would be the when the N is less than 2, as then the Fibonacci number would be itself. The recursive call would be calling the method for calculating the (n-1)th and (n-2)nd Fibonacci number and adding it to get the result for Nth number.
The concept of Recursion solves many problems and makes the process easier as when calculating through Iterative process. Thus, if a person masters the concept of Recursion, one could solve many problems in lesser time and lesser lines of code. However, Recursion in Ruby sometimes produces “SystemStackError: stack level too deep” when a large number is used as an input(This number varies with the system). This means that we would have to use iterative approach to a problem involving large inputs.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.