Enumerable Patterns
Each With Index
each_with_index gives a block both the current value and its position.
Each With Index
each_with_index.rb
start_number =
items = ["red", "blue", "green"]
items.each_with_index do |item, index|
label = "#{index + start_number}:#{item}"
puts label
end
start_number =
items = ["red", "blue", "green"]
items.each_with_index do |item, index|
label = "#{index + start_number}:#{item}"
puts label
end
start_number =
items = ["red", "blue", "green"]
items.each_with_index do |item, index|
label = "#{index + start_number}:#{item}"
puts label
end
index-aware iteration
Index-aware iteration is useful when output depends on position as well as value.