Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Iterates over array indexes.
When a block given, passes each successive 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 }
Output:
0
1
When no block given, returns a new Enumerator:
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.
 
               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;
}
            

Was this page useful?