×

ruby · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

squashes a whole list into one value.

You have built running totals by hand: a variable before the loop, then += inside it. .reduce does both jobs. Give it a starting value, and its block gets two variables: the answer so far, and the next item.

The first variable is called the . Whatever the block hands back becomes the accumulator for the next item. When the items run out, .reduce hands back the final accumulator.

For plain adding up, .sum with a block is shorter: basket.sum { |item| item[:price] }.

prices = [3, 5, 2]
total = prices.reduce(0) { |so_far, price| so_far + price }
puts total
puts [2, 3, 4].reduce(1) { |so_far, n| so_far * n }
basket = [{ name: "tea", price: 2 }, { name: "cake", price: 3 }]
puts basket.sum { |item| item[:price] }

The value in brackets is where the accumulator starts, so use 0 for adding and 1 for multiplying.