Monday, September 15, 2008

Ruby 1.8.7's Enumerator Class

Early in my Ruby career, I found myself needing access to the index while using Enumerable methods such as map and select. I quickly discovered the obscurely documented enum_for method:

Since MacPorts is now on Ruby 1.8.7, I read the 1.8.7 summary log and noticed a bunch of existing methods that now "Return an enumerator if no block is given." I soon realized that the above can now be written as:

It's a seemingly simple and minor improvement, but I think this change will encourage developers to use Enumerator more often with Ruby. For example, the enum_for method is never used in Rails 2.1. Contrarily, I bet that the new "Return an enumerator if no block is given" change will be used in Rails (eventually).

Arbitrary Uses

Since Integer#downto returns an Enumerator, let's write factorial:

Why not sort the letters in a word? Let's combine each_char with sort:

Since Enumerator is just an object, we can pass it around, and customize how other methods behave. For example, here I determine whether the items are processed in ascending or descending order:

All of this fun can be added to prior versions of Ruby by opening classes. I think this might work...

Please comment and let me know if there are better uses for this change!



I think it should be alias_method_chain method, :enumerator

Matthew Higgins said...

Yes, you are correct.

Roger Pack said...

backports gem is useful, too