Method: Enumerable#each_with_index

Defined in:
enum.c

#each_with_index(*args) {|element, i| ... } ⇒ self #each_with_index(*args) ⇒ Object

Invoke self.each with *args. With a block given, the block receives each element and its index; returns self:

h = {}
(1..4).each_with_index {|element, i| h[element] = i } # => 1..4
h # => {1=>0, 2=>1, 3=>2, 4=>3}

h = {}
%w[a b c d].each_with_index {|element, i| h[element] = i }
# => ["a", "b", "c", "d"]
h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}

a = []
h = {foo: 0, bar: 1, baz: 2}
h.each_with_index {|element, i| a.push([i, element]) }
# => {:foo=>0, :bar=>1, :baz=>2}
a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]

With no block given, returns an Enumerator.

Overloads:

  • #each_with_index(*args) {|element, i| ... } ⇒ self

    Yields:

    • (element, i)

    Returns:

    • (self)


3023
3024
3025
3026
3027
3028
3029
3030
# File 'enum.c', line 3023

static VALUE
enum_each_with_index(int argc, VALUE *argv, VALUE obj)
{
    RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);

    rb_block_call(obj, id_each, argc, argv, each_with_index_i, INT2FIX(0));
    return obj;
}