Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Use each_with_object in Ruby: Syntax and Examples

In Ruby, each_with_object iterates over a collection and passes each element along with a given object to a block, returning that object after iteration. It is useful for building or accumulating results without modifying the original collection.
📐

Syntax

The each_with_object method takes an object as an argument and yields each element of the collection along with that object to the block. The method returns the object after iteration.

  • collection.each_with_object(object) { |element, obj| ... }
  • element: current item from the collection
  • obj: the object passed in, used to accumulate results
ruby
array = [1, 2, 3]
result = array.each_with_object([]) do |num, obj|
  obj << num * 2
end

puts result.inspect
Output
[2, 4, 6]
💻

Example

This example shows how to use each_with_object to create a hash that counts the frequency of words in an array.

ruby
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
frequency = words.each_with_object(Hash.new(0)) do |word, counts|
  counts[word] += 1
end

puts frequency.inspect
Output
{"apple"=>3, "banana"=>2, "orange"=>1}
⚠️

Common Pitfalls

One common mistake is to try modifying the original collection inside the block instead of the object passed to each_with_object. Another is to expect each_with_object to return the original collection instead of the object.

Wrong way:

ruby
array = [1, 2, 3]
result = array.each_with_object([]) do |num, obj|
  array << num * 2  # Modifying original array - causes infinite loop
end
📌

Right way:

ruby
array = [1, 2, 3]
result = array.each_with_object([]) do |num, obj|
  obj << num * 2  # Append to the object, not the original array
end

puts result.inspect
Output
[2, 4, 6]
📊

Quick Reference

MethodDescription
each_with_object(obj) { |element, obj| ... }Iterates and passes element and obj, returns obj
objObject used to accumulate or build results
ReturnsThe object passed in, after iteration completes
✅

Key Takeaways

each_with_object passes each element and a given object to a block and returns that object.
Use it to build or accumulate results without changing the original collection.
Always modify the passed object inside the block, not the original collection.
It is handy for creating hashes, arrays, or other accumulators in a clean way.