1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

Loops the "Ruby Way"

By

Loops the "Ruby Way"

Though the more traditional while and until loops are used in Ruby programs, closure-based loops are more common. It isn't even necessary to understand what closures are or how they work in order to use these loops; in fact they're viewed as normal loops despite being very different under the hood.

The Times Loop

The times loop can be used on any variable containing a number or used on a number itself. In the following example, the first loop is run 3 times and the second loop is run however many times is input by the user. If you input 12, it would run 12 times. You'll notice that the times loop uses the dot syntax (3.times do) rather than the keyword syntax used by the while and until loop. This has to do with how the times loop works under the hood but it's used in the same way a while or until loop is used.

#!/usr/bin/env ruby

3.times do
  puts "This will be printed 3 times"
end

print "Enter a number: "
num = gets.chomp.to_i

num.times do
  puts "Ruby is great!"
end

The Each Loop

The each loop is perhaps the most useful of all the loops. The each loop will take a list of variables and run a block of statements for each of them. Since almost all computing tasks use lists of variables and have to do something with each of them in the list, the each loop is by far the most common loop in Ruby code. One thing to note here is the argument to the loop's block of statements. The value of the current variable the loop is looking at is assigned to the variable name in pipe characters, which is |n| in the example. The first time the loop runs, the n variable will be equal to "Fred," the second time the loop runs it will be equal to "Bob" and so on.

#!/usr/bin/env ruby

# A list of names
names = [ "Fred", "Bob", "Jim" ]

names.each do|n|
  puts "Hello #{n}"
end
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Ruby's Basic Features
  6. While, Until, Each and Times Loops in Ruby

©2014 About.com. All rights reserved.