recursion, recursion, recursion

Okay I learned one of the coolest ruby techniques that I’ve seen thus far, it’s called recursion and it’s awesome.

Recursion allows you to define a function(method) then call itself within the body of that function. On first glance it looks very confusing but basically you are using the function within the function itself. Even trying to explain it here is very tough. Let’s try an example.

def countdown(n)
  if n == 0
    puts "Blastoff!"
  else
    puts n
    countdown(n-1)
  end
end

In this program called countdown we take a number “n” and pass it through the code block. The final result is a countdown of numbers until you get to 1 and then it prints out “Blastoff!”. You could also write this program using a while loop:

while n > 0
puts n
n = n -1
end
puts “Blastoff!”

but with recursion we can save time and energy by calling the function on itself. Using recursion we can write less code and make our program look cleaner. For instance let’s say we have countdown(10). Following the path in the code block we check if n is equal to 0. Since it’s not we move on to the else portion of the code block. We puts n and then find countdown(n-1) which is the same as countdown(9). At this point we have to go through the steps again using “n-1″. Ok let’s check if “n-1″ is equal to 0. 9 does not equal 0 so we go to the else portion of the code block, puts 9 and then run through countdown(9-1) or countdown(8). The program runs through this system until countdown(1) where countdown(n-1) would equal 0 and the program can end.

This was not a very thorough explanation I know. I’m still wrapping my head around it myself but I wanted to type it out to understand it better. I’ll have a more structured answer for you in a bit!

 
1
Kudos
 
1
Kudos

Now read this

How to write a switch statement in ruby

case a when 1..10 puts "It's between 1 and 10" when 8 puts "It's 8" when String puts "You passed a string" else puts "You gave me #{a} -- I have no idea what to do with that." end Programming languages are very similar to spoken... Continue →