×

ruby · level 2 · unit 1 · lesson 4

  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

.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.