liveBook · Manning

With_index

As explained in The Well-Grounded Rubyist, Fourth Edition

each_with_index is an Enumerable method that invokes a block for each element while supplying the element's ordinal index.

with_index adds a numerical index as an additional block argument to an enumeration. It is commonly used by chaining it to an enumerator, as in each.with_index, map.with_index, or another enumerator-producing operation. section 10.11.2 section 10.5.2

Number elements while iterating

names.each.with_index(1) do |name, i| puts "#{i} #{name}" end The optional argument sets the first index value, so the output can begin at 1 instead of Ruby's usual zero-based counter. section 10.5.2

Use the form that matches the operation:

  • Use each_with_index when directly iterating and receiving an element plus its ordinal position. section 10.5.2
  • Use each.with_index when you want the same behavior through an enumerator and the ability to provide a starting index. section 10.5.2
  • Chain with_index onto other enumerators, such as map.with_index, to index transformed values without a composite map_with_index method. section 10.11.2
  • Remember that the counter is separate from a collection's own key: hash iteration supplies key/value content plus a meta-index. section 9.1
scale.play.with_index(1) {|note,i| puts "Note #{i}: #{note}" } #1

A numbered musical-scale example shows with_index applied directly to an enumerator and starting at one. section 10.11.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block arguments, enumerator chaining, starting indices, and hash meta-indexes, while stopping short of enumerator internals.
Examples
Uses alphabet pairs, numbered presidents, colored arrays, hash pairs, and a numbered musical scale.
What it assumes
Assumes familiarity with blocks and collection iteration while developing understanding of Enumerable and Enumerator behavior.
What you can do after
Apply it via Ruby iteration chains to label, transform, or enumerate elements with zero-based or custom starting indices.
How it connects
Connects Enumerable, Enumerator, each, each_with_index, each_index, map, arrays, and hashes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.