Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Enumerable#each_with_index
() { (E, ::Integer index) -> untyped } -> self
() -> ::Enumerator[[ E, ::Integer ], self]
each_with_index(*args) {|element, i| ..... } → self
each_with_index(*args) → enumerator
enum.c
View on GitHub ↗
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;
}
Invoke self.each with *args. With a block given, the block receives each element and its index; returns self:
Example
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.
See also
#each_slice
#each_with_object
#each_entry
#entries
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0