How to Access Index With Ruby Array#map?

If you want the index for the array values you iterate over using Array#map (or Array#map!), then you can use the with_index method, which can be chained to Array#map like so:

array.map.with_index { |item, index| ... }

This makes it so that the first parameter passed in is the array element, and the second parameter is the index. For example:

letters = ["a", "b", "c", "d"]
new_letters = letters.map.with_index { |letter, index| [index, letter] }

print new_letters
#=> [[0, "a"], [1, "b"], [2, "c"], [3, "d"]]

You can also specify the starting value for the index by passing a (start) number as an argument to the with_index method, for example, like so:

letters = ["a", "b", "c", "d"]
new_letters = letters.map.with_index(1) { |letter, index| [index, letter] }

print new_letters
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.