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
