Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Enumerable#each_with_index
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)
{
struct MEMO *memo;
RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
memo = MEMO_NEW(0, 0, 0);
rb_block_call(obj, id_each, argc, argv, each_with_index_i, (VALUE)memo);
return obj;
}
With a block given, calls the block with 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.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0