This article was originally included in the September issue of the Engine Yard Newsletter. To read more posts like this one, subscribe to the [_Engine Yard Newsletter](http://www.engineyard.com/newsletter)._
In this series, Evan Phoenix, Rubinius creator and Ruby expert, presents tips and tricks to help you improve your knowledge of Ruby.
Ruby is a rich language that believes there should be more than one way to express yourself—the many ways of counting and iterating are no exception.
Most Ruby programmers are familiar with the most common one:
Integer#times counts from 0 up to 99, yielding the current number to the block. This a simple, expressive way to execute some code a number of times.
But there are cases where you want to start counting at a number other than 0, no problem:
This prints out 10, 11, 12, until it hit 20. It increments by 1, and you'll notice it is inclusive, meaning that in this case we yield 11 items, not 10.
Going up is nice, but sometimes you need to go down, so use #upto's sister:
If you need a little more control over your iteration, you can use:
This will print 10, 12, 14, 16, 18, 20.
Now, in this case, we've introduced a Range, which most Ruby programmers are familiar with. It is basically an object that expresses a beginning and an end — in this case, 10 and 20. Range has another trick up it's sleeve:
You'll notice the 3 dots instead of 2. This indicates that this range is exclusive of the end, not inclusive. So 20 is the terminator, but is not in the set of valid values itself.
Range also support #each:
This works exactly the same as Integer#upto. I personally prefer Integer#upto, because I feel it expresses the operation better.
Another domain is counting on a collection. Before 1.8.7 and 1.9, there was pretty much only one method to help you with doing that: Array#each_with_index.
This prints out [:foo, 0], [:bar, 1], and [:baz, 2].
This is nice, but it's pretty limiting because the only place you've got that index is with simple iteration. Say you wanted to map the Array and take the position into account — you'd have to do:
It's kind of messy to just take the position into account. So with 1.8.7 and 1.9, Enumerator support was baked into most methods which makes this much simpler!
For those that haven't seen Enumerators yet, you're saying "Hey! Where did the block to map go!" Well there isn't one.
Array#map, when passed no block, returns a Enumerator object. This object, when you call #each, calls the original method on the original object and passes the block along. To begin with, this provides external iteration, but it also gives Ruby a place to add iteration alteration methods, such as
Enumerator#with_index. Now you never need to use a while loop again!
See you next time!
1.8.7 is a bit inconsistent about when Enumerators are returned. You can instead do:
Or, as a commenter pointed out: