Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
59: each_with_object and each_slice
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_sliceto process theproductsarray in batches of 3. For each batch, print a message saying"Processing batch [batch_number]...". - Inside that same loop, use
each_with_objecton 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
There are no comments for now.