|
The above code is pretty easy to understand, what "self" does should be pretty self-explanatory: it checks itself to see if it equals 1, and if does then factorial of 1 is equal to self, meaning 1; else, it multiplies itself with the factorial of the number one less than itself.
Here's another formula for calculating yet another popular recursion problem, th Fibonacci sequence:
F(n) = F(n − 1) + F(n − 2)
For every problem that you want to solve through recursion, you need to find a recursive formula first, once you do that it's almost a piece of cake implementing it with code.
You will also need to find out the most basic case that cannot be computed and must be used as a starting base for the recursion, notice in the code above this sequence:
if n == 1
n
This tell the program that 1! equals 1, starting from 1!, all other factorials can be calculated based on it.
There is nothing particular about recursion in Ruby, you've already noticed that it's done with methods which we'll discuss in a later chapter in more detail.
|