Skip to content

Latest commit

 

History

History
29 lines (22 loc) · 849 Bytes

map-with-index-over-an-array.md

File metadata and controls

29 lines (22 loc) · 849 Bytes

Map With Index Over An Array

The #map method on its own allows you to interact with each item of an array, producing a new array.

[1,2,3].map { |item| item * item }
#=> [1,4,9]

If you also want access to the index of the item, you'll need some help from other enumerable methods. As of Ruby 1.9.3, you can chain on #with_index:

[1,2,3].map.with_index { |item, index| item * index }
#=> [0,2,6]

This method has the added benefit of allowing you to specify the starting value of the index. It normally starts with 0, but you could just as easily start at 1:

[1,2,3].map.with_index(1) { |item, index| item * index }
#=> [1,4,9]

source