End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#each_with_index
enum.each_with_index(*args) { |obj, i| block } → enum
enum.each_with_index(*args) → an_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;
}
Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().
If no block is given, an enumerator is returned instead.
Example
hash = Hash.new %w(cat dog wombat).each_with_index { |item, index| hash[item] = index } hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
See also
#each_slice
#each_with_object
#each_entry
#entries
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1