Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Enumerable#each_with_object
each_with_object(object) { |(*args), memo_object| ... } → object
each_with_object(object) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_each_with_object(VALUE obj, VALUE memo)
{
RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
return memo;
}
Calls the block once for each element, passing both the element and the given object:
Example
(1..4).each_with_object([]) {|i, a| a.push(i**2) } # => [1, 4, 9, 16] {foo: 0, bar: 1, baz: 2}.each_with_object({}) {|(k, v), h| h[v] = k } # => {0=>:foo, 1=>:bar, 2=>:baz}
With no block given, returns an Enumerator.