Recursion exercises in Ruby
Every skilled programmer knows about recursion. It can be a powerful tool for writing algorithms to solve problems. In plain English, recursion is the calling of a function from within that same function. You divide one task into many little steps and perform it again and again.
Every recursion function should consist of:
- Base recursion step
- Exit condition
- Limit for input value
For example, the task is: You were given a natural number ‘number’. Return a string with all numbers from 1 to ‘number’ using recursion separating them by spaces. The function is:
The limit is critically important if you write code for production! Because, if you perform the function with a number is 500 000 you will get an error: ‘Stack level too deep (SystemStackError)’. You should avoid it in production.
Recursion is not a silver bullet. Every algorithm can be implemented without recursion. It may be hard to implement, but it has not SystemStackError and sometimes it is faster. Here is Fibonacci sequence example with and without recursion:
If you want to try solve tasks with recursion, here is GitHub repository with exercises and answers: https://github.com/kopylovvlad/ruby_recursion_exercises
Happy coding 😀