Iteration with index

suggest change

Sometimes you want the position (index) of the current element while iterating. Ruby provides with_index for that. It can be applied to enumerators. The index is passed to the 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 takes an optional starting 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]

each_with_index is similar to each.with_index, except you cannot pass a starting index, so the first index is always 0.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents