How to Use each_with_index in Ruby: Syntax and Examples
In Ruby,
each_with_index is used to loop over a collection while accessing both the element and its index. It yields two values to the block: the element and its index, allowing you to use both inside the loop.Syntax
The each_with_index method is called on an enumerable object like an array. It takes a block with two parameters: the current element and its index.
Syntax pattern:
collection.each_with_index do |element, index|
# code using element and index
endruby
array = ['a', 'b', 'c'] array.each_with_index do |element, index| puts "Element: #{element}, Index: #{index}" end
Output
Element: a, Index: 0
Element: b, Index: 1
Element: c, Index: 2
Example
This example shows how to print each item in an array along with its index using each_with_index. It demonstrates accessing both values inside the block.
ruby
fruits = ['apple', 'banana', 'cherry'] fruits.each_with_index do |fruit, i| puts "Fruit number #{i + 1} is #{fruit}" end
Output
Fruit number 1 is apple
Fruit number 2 is banana
Fruit number 3 is cherry
Common Pitfalls
One common mistake is using each instead of each_with_index when you need the index, which means you won't have access to the index inside the block.
Another is mixing up the order of block parameters; the first is always the element, the second is the index.
ruby
numbers = [10, 20, 30] # Wrong: only element, no index numbers.each do |index| puts "Index: #{index}, Number: " end # Right: element then index numbers.each_with_index do |number, index| puts "Index: #{index}, Number: #{number}" end
Output
Index: 10, Number:
Index: 0, Number: 10
Index: 1, Number: 20
Index: 2, Number: 30
Quick Reference
- Purpose: Iterate with element and index.
- Receiver: Any enumerable (Array, Hash, etc.).
- Block parameters:
|element, index|. - Returns: The original collection.
Key Takeaways
each_with_index lets you access both element and index during iteration.The block receives two arguments: the element first, then the index.
Using
each alone won't give you the index.It works on any enumerable like arrays and hashes.
The method returns the original collection after iteration.
