Ruby Language Iteration with index


Example

Sometimes you want to know the position (index) of the current element while iterating over an enumerator. For such purpose, Ruby provides the with_index method. It can be applied to all the enumerators. Basically, by adding with_index to an enumeration, you can enumerate that enumeration. Index is passed to a block as the second argument.

[2,3,4].map.with_index { |e, i| puts "Element of array number #{i} => #{e}" }
#Element of array number 0 => 2
#Element of array number 1 => 3
#Element of array number 2 => 4
#=> [nil, nil, nil]

with_index has an optional argument – the first index which is 0 by default:

[2,3,4].map.with_index(1) { |e, i| puts "Element of array number #{i} => #{e}" }
#Element of array number 1 => 2
#Element of array number 2 => 3
#Element of array number 3 => 4
#=> [nil, nil, nil]

There is a specific method each_with_index. The only difference between it and each.with_index is that you can't pass an argument to that, so the first index is 0 all the time.

[2,3,4].each_with_index { |e, i| puts "Element of array number #{i} => #{e}" }
#Element of array number 0 => 2
#Element of array number 1 => 3
#Element of array number 2 => 4
#=> [2, 3, 4]