instance method
Array#each_index
() { (::Integer index) -> void } -> self
() -> ::Enumerator[::Integer, self]
each_index {|index| ... } → self
each_index → new_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;
}
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.