Ruby/Recursion

From Meshplex

Jump to: navigation, search
Image:Ruby_on_rails_tutorials.jpg
Ruby for complete beginners
Ruby Introduction
What can I use RoR for?
Reasons for choosing RoR over other popular programming languages such as php or asp.net .What makes Ruby so much more special
Where can I find RoR? In what “forms” does it come?
How to install RoR.Solutions for both the novice and professional programmers on Windows,Mac OS X and Linux.Prerequisites.
Ruby programming tutorials for beginners:
Ruby Basics
Ruby Variables, Datatypes, Operators
Ruby Symbols
Ruby Statements
Ruby Converting data to another type: type conversion or typecasting
Ruby Arrays, Hashes, Ranges
Ruby Functions and built in functions
Ruby Control structures
Ruby Regular expressions and blocks
Ruby Loops
Ruby Recursion
** More Ruby Recursion
Ruby Data Structures
Ruby Methods, Classes, Modules, Namespaces
Ruby Exceptions
Ruby Object Oriented Programming
Ruby Multithreading
Ruby File Handling.Input and Output
Ruby Basic GUI
Ruby and databases.Ruby on Rails and MySQL
Ruby Basic CGI.Using fastCGI
Ruby Basic Networking and web programming
Ruby Basic Graphics
Ajax and Rails.Web 2.0 and what it means
Ruby Testing, Debugging, Automation of tasks
Ruby Apache,Capistrano, Mongrel,lighttpd – reviews and tips
Finding a Ruby on Rails ready web hosting company
BONUS: mini tutorial for a simple RoR application

[edit] Ruby Recursion

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)

Image:Fact.gif

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

Previous Next