|
Definition provided by Wikipedia:
"In mathematics and computer science, recursion is a particular way of specifying (or constructing) a class of objects (or an object from a certain class) with the help of a reference to other objects of the class: a recursive definition defines objects in terms of the already defined objects of the class. "
Read more about general recursion concepts here on Wikipedia
One of the classic examples that are taught to people that want to learn how to program is the factorial (when they need to learn recursion).
For example:
n! (notation for factorial) = 1*2*3...*n
5!=1*2*3*4*5
How would you do that in Ruby? Like this:
def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end
You might notice a strange thing at first, that the "factorial" calls itself later in the code :
n * factorial(n-1)
This is a recursive call.The whole idea behind the few lines above is the fact that the formula for finding out n! is actually calculated based on (n-1)! like this: n!=n*(n-1)!
A formula like this would allow us to solve the problem recursively, by calculating every factorial under n!
Now, if you want to find out how much 3! is, you use the factorial you just defined above:
factorial(3)
Here's another way of solving a factorial with methods(discussed in more detail later):
class Integer
def factorial
if self == 0
1
else
self * (self - 1).factorial
end
end
end
You find out how much 3! is by calling the method:
3.factorial
|