ruby · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
.each hands you every key and value, pair by pair.
.each on a hash gives the block two variables: one for the key and one for the value. Name them well, like |fruit, count|, and the loop reads like a sentence. .keys gives an array of every key, and .values an array of every value, so .values.sum adds up the whole hash.
To keep a , make the hash with Hash.new(0). Every missing key then starts at a default of 0, so votes[pet] += 1 works first time. += is short for votes[pet] = votes[pet] + 1.
basket = { apples: 3, pears: 2, plums: 5 }
basket.each do |fruit, count|
puts "#{fruit}: #{count}"
end
puts basket.values.sum
votes = Hash.new(0)
["cat", "dog", "cat"].each do |pet|
votes[pet] += 1
end
p votes Ruby keeps a hash in the order you added its pairs.
guess first
Count the votes. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
votes = Hash.new(0)
["red", "blue", "red", "red"].each do |colour|
votes[colour] += 1
end
p votes
your turn
Your turn. Total up a shopping trip.
Add two more items to the receipt with their prices in pence, then press run to see each line and the total.
fix it
The ice cream van cannot add up. Can you fix it?
- Read the error. A TypeError means two kinds of value got mixed up. What does
dayhold each turn? - With one block variable, each turn gets the whole pair, key and value together. Give the block two variables.
- Change line 3 to sales.each do |day, count| and line 4 to total += count.
nailed it
you can walk through any hash. :D
.each do |key, value|visits every pair in order..keysand.valuesgive arrays you can sum or search.Hash.new(0)makes counting with+= 1safe.
new words in your collection
- tally
This lesson isn’t saved. A free account remembers every lesson you finish.