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
array.c
View on GitHub ↗
static VALUE
rb_ary_each_index(VALUE ary)
{
long i;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
for (i=0; i<RARRAY_LEN(ary); i++) {
rb_yield(LONG2NUM(i));
}
return ary;
}
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.