Wednesday 29 February 2012

Using the Times Loop in Ruby on Rails


One of the most fundamental parts of programming is learning how to use loops, i.e. recursion or iteration, to your advantage. Once you understand the concept you will reach a level that is what I believe to be the main place that math or computer-phobes stumble, the concept of loops. This loop device is used in every programming language out there, there is just difference in syntax. It is very simple, but powerful.
Using the ‘Times’ Loop
The times loop is one of my favorite ways to loop things in Ruby, when using a language that doesn’t have something like it you really miss it. It makes it very simple and efficient to perform a quick iteration without need for setting up any counter variables or anything of that nature. Here is an example of the convenience offered by the times loop.
Instead of doing this –
puts "Hello World"
puts "Hello World"
puts "Hello World"
puts "Hello World"
puts "Hello World"
You can just do this –
5.times do
 puts "Hello World"
end


They will produce exactly the same result. Yes, it’s a simple example but it’s the concept that is important here. Remember DRY when programming, as in Dont Repeat Yourself! Using loops like the timesloop so that you aren’t copy and pasting all over the place when you are just repeating yourself.
Likewise if the # of times you want to iterate isn’t predetermined then you can use a variable in it’s place likeso—

puts "How many times should I say Hello World?"
x = gets.to_i

x.times do
 puts "Hello World"
end


Here we are just asking the console for an integer, and then we take what is entered and name it variable x. Then we just replace the previously hardcoded number with our variable and we are good to go — this will run however many times you want it to without needing to make any changes to your code. Hurray the Ruby times Loop!

No comments:

Post a Comment