Mike Austin's Blog

Monday, March 13, 2006

Clever Ruby 2.0? enumerations

Ok, so you can iterate over a collection:
(1..10).each { |v, i| puts v * i }
And you can iterate over a collection with an index:
(1..10).each_with_index { |v, i| puts v * i }
But if you want map_with_index, select_with_index, etc. it causes an explosion of methods to create. What if each is called without a block, and passed along to the next enumerator:
(1..10).each.with_index { |v, i| puts v * i }
Nice! Why? Because now you can do things like:
(1..10).collect.with_index { |v, i| v * i }
without pre-defining this functionality. It's more general, has the same number of keystrokes, and the syntax is only a one character difference. More info here