Topic 15
Topic 15
Ruby source files are converted directly from the English source tree.
Overview
Why this topic matters ๐ก
Topic 14 taught transformation pipelines. Topic 15 teaches the next step: problems where you need to build one result from many inputs. This is where reduce and each_with_object become practical tools rather than abstract ideas.
Learning outcomes ๐ฏ
By the end of this topic, students should be able to:
Assessment focus โ
Students should be able to defend the accumulator they chose and explain why it is clearer than a manual loop with external mutable state.
Short Note
Not every collection problem is a map . Some problems ask for:
That is where accumulator thinking matters.
Imperative style often looks like this:
total = 0 rows . each do |row| total += row [: amount ] end shortnote.md ruby Ruby accumulator style can look like this:
rows . reduce ( 0 ) { |sum , row| sum + row [: amount ] } shortnote.md ruby For hashes or grouped structures, each_with_object often reads even better:
rows . each_with_object ({}) do |row , grouped| grouped [ row [: currency ]] || = 0 grouped [ row [: currency ]] += row [: amount ] end shortnote.md ruby Ruby beauty in this topic:
Ruby caution in this topic:
Reflection prompt:
Worked Examples
Example 1: Invoice total ๐ก
Old style:
total = 0 invoices . each do |invoice| total += invoice [: amount ] end worked_examples.md ruby Accumulator style:
invoices . reduce ( 0 ) { |sum , invoice| sum + invoice [: amount ] } worked_examples.md ruby Why the second version helps: