Ruby/Recursion2

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
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
Recursion page 2

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.

Image:Fact2.gif

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.

Previous Next
Personal tools