Ruby — Counting values with Hash.new
A Ruby Hash created with Hash.new(0) supplies zero for a missing key. Incrementing the entry stores the first count and can accumulate later occurrences.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
counts = {"A" => 2}
puts counts["A"]
2
Count labels without relying on storage order
Hash.new(0) supplies an integer default for missing keys. The += operation stores the incremented value back into the hash. A separate array supplies the display order.
A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.
Run the example
Ruby 2.7 or later. Run these commands from the directory containing the example.
ruby lesson.rb
counts = Hash.new(0)
%w[red blue red].each { |color| counts[color] += 1 }
%w[red blue].each { |color| puts "#{color} #{counts[color]}" }
red 2 blue 1
The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.
Try it yourself
Insert another blue before the last red. What changes?
Check your answer
Both keys now have a count of two. The requested display order stays red, then blue.