Module 02 Β· Collections & Blocks β Lesson 5 of 6 Β· ~11 min
Crunch: sum, sort_by, min_by
sum β add up a field with a block
sum totals a collection of numbers directly, but its real power shows up with a block: give it a block and it sums WHATEVER the block returns for each item, without a separate map step first:
bookings = [{ price_cents: 2500 }, { price_cents: 3000 }, { price_cents: 2000 }]
total_cents = bookings.sum { |b| b[:price_cents] }
# 7500Read bookings.sum { |b| b[:price_cents] } as "for each booking, take its price_cents, and add all of those together."