Logo

How to map/collect with index in Ruby?

You can use any of the following approaches to iterate over an array (or any Enumerable) with index while transforming each element:

1. Using each_with_index and collecting manually

fruits = ["apple", "banana", "cherry"] result = [] fruits.each_with_index do |fruit, idx| result << "#{idx} - #{fruit.upcase}" end puts result.inspect # => ["0 - APPLE", "1 - BANANA", "2 - CHERRY"]

Here:

  • each_with_index yields both the element and its index to the block.
  • You manually build a new array (result) by pushing transformed elements.

2. Using map.with_index (a more functional style)

fruits = ["apple", "banana", "cherry"] result = fruits.map.with_index do |fruit, idx| "#{idx} - #{fruit.upcase}" end puts result.inspect # => ["0 - APPLE", "1 - BANANA", "2 - CHERRY"]

With map.with_index:

  • map returns an Enumerator if no block is given.
  • Then with_index is called on that enumerator.
  • The resulting enumerator is then used with the final block, allowing both value and index.

3. Using (0...array.size).map

If you prefer to iterate over a range of indexes explicitly:

fruits = ["apple", "banana", "cherry"] result = (0...fruits.size).map do |idx| "#{idx} - #{fruits[idx].upcase}" end puts result.inspect # => ["0 - APPLE", "1 - BANANA", "2 - CHERRY"]

This approach is sometimes handy if you need the index separately for a different data source or if you’re dealing with multiple arrays of the same size.

Going Further

To master these and other Ruby patterns—and level up your system design knowledge—check out these DesignGurus.io resources:

For personalized feedback from ex-FAANG engineers, explore the Coding Mock Interview or System Design Mock Interview.

CONTRIBUTOR
TechGrind