How to Access Index With Ruby Array#map?

Find out how to use the Ruby Array#map method with index

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"]]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.