Friday, February 9, 2007

Iterate this!

One of the syntactical elements of Ruby that I found slightly baffling was this sort of thing:

["Tuna", "Pawsie", "Bosco"].each {|pet| puts "#{pet}, get off the couch!"}


Intuitively, I could discern what was going on. Mechanically, however, I needed more details to grasp it completely. Once again, while on the elliptical machine at the gym, I came across the section in the Pickaxe describing blocks and iterators. So it turns out that the each method above is a Ruby iterator method. That's a slightly different approach than in other languages where an iterator is an object typically used in a loop which allows you to walk through a set of objects. What's neat (for me, at least) is that you pass in the block of code that you want the iterator method to execute for every object it iterates through. This would be equivalent to a typical iterator while loop in Java where the body of the loop is equivalent to the code block above.

But what actually makes this work, especially when you see multiple parameters specified between the vertical bars? It turns out that the block of code passed into the iterator is executed when the iterator method executes a yield statement. The yield statement can have zero or more parameters which are then sent to the code block. So, in the each iterator method, it walks through each element in the array and passes each one separately to the code block I passed in, resulting in the following output:

Tuna, get off the couch!

Pawsie, get off the couch!

Bosco, get off the couch!


No comments: