×

ruby · level 1 · unit 6 · 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

walks through an array, one item at a time.

.each runs a block once for every item, in order. Name a variable between the bars, like |price|, and on each turn it holds the next item. It works like times, but hands you items instead of numbers.

To add up an array, keep a : a variable that starts at 0 before the loop and grows on every turn. Show it after the end, once every item is counted.

Make the total before the loop. A variable first made inside a block disappears when the block ends, so Ruby cannot find it afterwards.

prices = [2, 5, 3]
total = 0
prices.each do |price|
  total = total + price
end
puts total

Name the item after the array: prices holds many, price holds one.