Method: Array#each_index

Defined in:
array.c

#each_index {|index| ... } ⇒ self #each_indexObject

With a block given, iterates over the elements of self, passing each array index to the block; returns self:

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:

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

Output:

0
1

With no block given, returns a new Enumerator.

Related: see Methods for Iterating.

Overloads:

  • #each_index {|index| ... } ⇒ self

    Yields:

    Returns:

    • (self)


2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
# File 'array.c', line 2680

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;
}