reduce and each_with_object
Aggregate collections.
reduce and each_with_object is a free Ruby Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is reduce?
reduce (alias inject) combines all elements into a single value. The block receives an accumulator and the current element.
sum = [1, 2, 3, 4].reduce(0) { |acc, n| acc + n }
puts sumHow the Accumulator Works
The accumulator carries the running result between iterations. Whatever the block returns becomes the next accumulator.
[1, 2, 3].reduce(0) do |acc, n|
puts "acc=#{acc} n=#{n}"
acc + n
endreduce Without a Start
Without an initial value, the first element becomes the accumulator and iteration starts from the second.
puts [10, 20, 30].reduce { |acc, n| acc + n }reduce with a Symbol
For simple operators, pass a symbol like :+ or :* instead of a block.
puts [1, 2, 3, 4].reduce(:+)
puts [1, 2, 3, 4].reduce(:*)Finding a Maximum
reduce can compute things beyond sums, such as the largest value.
nums = [3, 9, 2, 7]
max = nums.reduce { |acc, n| n > acc ? n : acc }
puts maxBuilding a String
The accumulator can be any type, including a string you build up.
letters = ["r", "u", "b", "y"]
word = letters.reduce("") { |acc, c| acc + c.upcase }
puts wordWhat Is each_with_object?
each_with_object is like reduce but you give it a mutable object that is returned automatically. You change the object inside the block.
result = [1, 2, 3].each_with_object([]) do |n, arr|
arr << n * 2
end
puts result.inspectBuilding a Hash
each_with_object is perfect for building hashes because you do not need to return the object each time.
words = ["apple", "pear"]
lengths = words.each_with_object({}) do |w, h|
h[w] = w.length
end
puts lengthsCounting Occurrences
Combine a default hash with each_with_object to tally items.
votes = ["a", "b", "a", "a"]
tally = votes.each_with_object(Hash.new(0)) do |v, h|
h[v] += 1
end
puts tallyreduce vs each_with_object
Use reduce when each step returns a new value (sums, products). Use each_with_object when you mutate one container (arrays, hashes).
puts [1, 2, 3].reduce(:+)
puts [1, 2, 3].each_with_object([]) { |n, a| a << n }.inspectThe tally Shortcut
For counting, Ruby has a built-in tally method that does the work for you.
puts ["a", "b", "a"].tallyQuick Check
Check aggregation skills.
Recap
You can now aggregate collections:
reduce/injectwith accumulator, start value, or symboleach_with_objectfor building arrays and hashestallyfor quick counts- choose reduce for new values, each_with_object for mutable containers
Next course: numbers and math.
puts (1..5).reduce(:*)Frequently asked questions
Is the “reduce and each_with_object” lesson free?
Yes — the full text of “reduce and each_with_object” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.
What will I learn in “reduce and each_with_object”?
Aggregate collections. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Ruby Academy?
No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “reduce and each_with_object” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Ruby Academy lesson?
Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating Ranges
- The Enumerable Module
- map, select, reject
- reduce and each_with_object