1. Computing

The Forgotten Keyword: The 'for' Loop

By

In most imperative languages, one of the primary loops is the 'for' loop. You may have even learned it early on in your Ruby career, but promptly forgotten about it. It just isn't idiomatic Ruby, you'll almost never see it in production code, but it does have some minor uses.

First, what does it do? The for keyword in Ruby (and it is a keyword, not a method) works much like the each method of enumerable objects. In fact, it will work with any object that can be used with each. Being a keyword, it doesn't take a block as an argument. Instead, you pass a variable name you'd like to use for each element in the enumerable object. So, instead of doing this each-style loop:


(1..10).each do|i|
 puts i
end

You could use this for-style loop:


for i in 1..10
 puts i
end

Note that there is no do block. This is a keyword, it's more like an if statement. Also note that the variable name i is not a block argument, and doesn't follow the same rules. This will introduce a new variable named i into the current scope and will remain available for use after the for statement ends.

So why would anyone want to use this over the idiomatic each loop? There aren't many cases where this is clearly better. You could do something like the following, that will find the first element in the enumerable object that is divisible by 10 then use the for loop's variable in later code.


for i in 97..205
 break if i % 10 == 0
end

# Later on, but still in the same scope
puts i

  1. About.com
  2. Computing
  3. Ruby

©2014 About.com. All rights reserved.