ruby · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One line, two snacks. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
snacks = ["crisps", "apple"]
snacks.each do |snack|
puts "I love #{snack}!"
end
your turn
Your turn. Add up your scores.
Type three scores from your last game, as numbers. Run it to see the running total add them up.
fix it
The till cannot find its total. Can you fix it?
- Read the error. It is a NameError on line 6. Where was total first made?
- total is made inside the block, so it disappears at the
end. It also restarts at 0 on every turn. - Move total = 0 up, above the
.eachline, then press run.
nailed it
you can walk through any array now. :D
.eachruns its block once for every item.- The name between the bars holds the current item.
- Start a running total at 0, before the loop.
new words in your collection
- each
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.