Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#each_with_object

each_with_object(object) { |(*args), memo_object| ... } → object
each_with_object(object) → enumerator

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.

See also #each_with_index #entries #each_slice #filter also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0