Enumerable#each_with_index
enum.each_with_index { |item, index| block } -> enum Returns:
Enumerator · Updated March 15, 2026 · Enumerable ruby enumerable iteration indexing
The each_with_index method iterates over each element in a collection while providing both the element and its index position. This is useful when you need to know where an element is located during iteration.
Basic Usage
fruits = ["apple", "banana", "cherry"]
fruits.each_with_index { |fruit, index| puts "#{index}: #{fruit}" }
# 0: apple
# 1: banana
# 2: cherry
Converting to Array
numbers = [10, 20, 30]
result = numbers.each_with_index.to_a
# => [[10, 0], [20, 1], [30, 2]]
Building a Hash from Index
items = ["a", "b", "c"]
indexed = items.each_with_index.each_with_object({}) { |(item, idx), hash|
hash[idx] = item.upcase
}
# => { 0 => "A", 1 => "B", 2 => "C" }
With an Offset Start
# Start index at 1 instead of 0
list = ["first", "second", "third"]
list.each_with_index.with_index(1) { |item, idx| puts "#{idx}. #{item}" }
# 1. first
# 2. second
# 3. third
Practical Examples
Numbered Lists
tasks = ["Buy milk", "Walk dog", "Write code"]
tasks.each_with_index { |task, i| puts "#{i + 1}. [ ] #{task}" }
# 1. [ ] Buy milk
# 2. [ ] Walk dog
# 3. [ ] Write code
Processing Paired Data
names = ["Alice", "Bob", "Carol"]
ages = [25, 30, 35]
names.each_with_index { |name, i| puts "#{name} is #{ages[i]} years old" }
# Alice is 25 years old
# Bob is 30 years old
# Carol is 35 years old
Finding by Index
items = ["a", "b", "c", "d", "e"]
# Find first item at even index
items.each_with_index.find { |_, idx| idx.even? }
# => "a"
# Get all items at odd indices
items.each_with_index.select { |_, idx| idx.odd? }.map(&:first)
# => ["b", "d"]
Transforming with Index
words = ["hello", "world", "ruby"]
numbered = words.each_with_index.map { |word, idx| "#{idx + 1}. #{word}" }
# => ["1. hello", "2. world", "3. ruby"]
With Hashes
stock = { apples: 5, bananas: 3, oranges: 2 }
stock.each_with_index { |(key, value), idx| puts "#{idx}: #{key} = #{value}" }
# 0: apples = 5
# 1: bananas = 3
# 2: oranges = 2
Chaining with Other Enumerators
[1, 2, 3, 4, 5].each_with_index
.select { |n, i| i.even? }
.map(&:first)
# => [1, 3, 5]
Return Value
Returns an Enumerator if no block is given. When a block is provided, returns the original collection.
[1, 2, 3].each_with_index { }
# => [1, 2, 3]
Performance Note
each_with_index is slightly slower than each due to the overhead of tracking the index. For simple iteration where index isn’t needed, use each instead.
See Also
Array#each_slice— iterate over consecutive elementsEnumerable#each_with_object— iteration that carries a memo objectEnumerable#find— find elements by conditionArray#map— transform elements