Automatic counter in Ruby for each?

As people have said, you can use

each_with_index

but if you want indices with an iterator different to “each” (for example, if you want to map with an index or something like that) you can concatenate enumerators with the each_with_index method, or simply use with_index:

blahs.each_with_index.map { |blah, index| something(blah, index)}

blahs.map.with_index { |blah, index| something(blah, index) }

This is something you can do from ruby 1.8.7 and 1.9.

Leave a Comment