Skip to content
instance method

Array#each_index

() { (::Integer index) -> void } -> self
() -> ::Enumerator[::Integer, self]
each_index {|index| ... } → self
each_index → new_enumerator

With a block given, iterates over the elements of self, passing each 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 }
a # => []

Output:

Example
0
1

With no block given, returns a new Enumerator.

Related: see Methods for Iterating.

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