Skip to Content
Course content

59: each_with_object and each_slice

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR from a junior developer who was trying to build a frequency map—basically counting how many times each tag appeared across a thousand blog posts. He was using inject (also known as reduce), but he kept hitting a wall. The code would run for one iteration and then suddenly return nil or the last tag in the list. He spent half his afternoon debugging why his hash was disappearing, only to realize that inject requires you to explicitly return the accumulator at the end of every block iteration.

It's a classic Ruby rite of passage. While inject is powerful, it's often the wrong tool when you just want to "pour" data into a pre-existing object. That's where each_with_object comes in. It handles the accumulator for you, so you can focus on the logic rather than the return value.

Building Accumulators without the Return Headache

When you use each_with_object, you pass in the object you want to build—like an empty hash or array—as an argument. Ruby then passes that object into the block as the second parameter. The magic is that each_with_object always returns that original object, regardless of what the last line of your block evaluates to.

tags = ["ruby", "rails", "ruby", "javascript", "rails", "ruby"]

# We pass an empty hash as the "object" we are building
tag_counts = tags.each_with_object(Hash.new(0)) do |tag, counts|
  counts[tag] += 1
end

puts tag_counts 
# Output: {"ruby"=>3, "rails"=>2, "javascript"=>1}

Notice how I didn't have to write counts as the last line of the block? I just mutated the hash and moved on. I personally find this much more readable than inject when the goal is simply to populate a collection. It signals to anyone reading your code: "I am taking this list and transforming it into this other object."

Processing Data in Bite-Sized Chunks

Now, let's talk about each_slice. In a perfect world, we could process 10,000 records in one go. In the real world, you'll hit API rate limits, memory overflows, or database timeouts. If you've ever had to write a pagination system or a batch uploader, you've felt this pain.

each_slice allows you to iterate through a collection in fixed-size groups. It effectively turns a flat array into an array of arrays, but it does so lazily during iteration, which is much more memory-efficient than manually slicing the array in a loop.

# Imagine we have a list of 100 user IDs that need to be synced to a CRM
user_ids = (1..100).to_a

# The CRM API only allows 20 IDs per request
user_ids.each_slice(20) do |batch|
  puts "Syncing batch: #{batch.inspect}"
  # CRM_API.sync(batch) 
end

I often use this when dealing with external services. Instead of sending 100 individual HTTP requests (which is slow) or one massive request (which might fail), each_slice lets you find that "Goldilocks" zone of batch size that keeps the system stable and performant.




📋 Practical Task

Exercise: Building a Batch-Processed Inventory Report

You have been given a flat array of product strings. Each string contains a category and a product name separated by a colon (e.g., "Electronics:Laptop"). Your goal is to process this data in two stages.

Requirements:

  • First, use each_slice to process the products array in batches of 3. For each batch, print a message saying "Processing batch [batch_number]...".
  • Inside that same loop, use each_with_object on the current batch to group the products by category. The result should be a hash where the keys are categories and the values are arrays of product names.
  • Finally, print the resulting hash for that specific batch.
products = [
  "Electronics:Laptop", "Electronics:Mouse", "Home:Lamp",
  "Home:Rug", "Clothing:Shirt", "Clothing:Hat",
  "Electronics:Monitor", "Home:Chair", "Clothing:Socks"
]

# Your code here
Rating
0 0

There are no comments for now.

to be the first to leave a comment.