ruby · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Follow the accumulator. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
walks = [1000, 2500, 4000]
steps = walks.reduce(500) { |so_far, walk| so_far + walk }
puts steps
your turn
Your turn. Add up a shopping basket.
Fill in a price in pence for each item, then press run to see the total.
fix it
Zero outfits? That cannot be right. Fix it!
- Work it through by hand, starting from the number in the brackets. What is 0 times anything?
- The accumulator starts at the value in the brackets. For multiplying, it needs to start at 1.
- Change reduce(0) to reduce(1) on line 2, then press run.
nailed it
you boiled a list down to one answer. :D
.reduce(start)carries an accumulator through every item.- The block's answer becomes the next accumulator.
- Start at 0 for adding and 1 for multiplying.
new words in your collection
- reduce
- accumulator
This lesson isn’t saved. A free account remembers every lesson you finish.