Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#each_index

array.each_index {|index| ... } → self
array.each_index → Enumerator

Iterates over array indexes.

When a block given, passes each successive array index to the block; returns self:

Example
a = [:foo, 'bar', 2]
a.each_index {|index|  puts "#{index} #{a[index]}" }

Output:

0 foo
1 bar
2 2

Allows the array to be modified during iteration:

Example
a = [:foo, 'bar', 2]
a.each_index {|index| puts index; a.clear if index > 0 }

Output:

Example
0
1

When no block given, returns a new Enumerator:

Example
a = [:foo, 'bar', 2]
e = a.each_index
e # => #<Enumerator: [:foo, "bar", 2]:each_index>
a1 = e.each {|index|  puts "#{index} #{a[index]}"}

Output:

0 foo
1 bar
2 2

Related: each, reverse_each.

See also #each #empty? #drop_while #eql? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0