Hash.new with Defaults
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 33 of 56.
By default, looking up a missing key in a hash returns nil:
scores = {}
puts scores["Alice"] # nilHash.new(default) changes that. Every missing key returns the value you passed in:
scores = Hash.new(0)
puts scores["Alice"] # 0This is the cleanest way to write a counter. You don't need to check if scores[name].nil? before incrementing:
counts = Hash.new(0)
["a", "b", "a", "c", "a"].each do |letter|
counts[letter] += 1
end
puts counts.inspect # {"a"=>3, "b"=>1, "c"=>1}Important: Hash.new(0) sets the default to 0 but does not store the key when you read it. The hash stays empty until you assign. So once you write counts[letter] += 1, the key gets added with the new value.
Challenge
EasyRead a comma-separated list of category:amount entries (e.g. food:12,gas:30,food:8,books:25,gas:15). Build a hash of totals per category using Hash.new(0), then print only the categories whose total is at least 20, one per line, sorted by total descending:
<category>: <total>For the example input above the output is:
gas: 45
books: 25
food: 20If no category reaches 20, print nothing.
Cheat sheet
By default, missing hash keys return nil. Use Hash.new(default) to return a different default value instead:
scores = Hash.new(0)
puts scores["Alice"] # 0This makes counters clean — no need to check for nil before incrementing:
counts = Hash.new(0)
["a", "b", "a"].each do |letter|
counts[letter] += 1
end
# {"a"=>2, "b"=>1}Note: reading a missing key does not store it. The key is only added once you assign a value (e.g. +=).
Try it yourself
entries = gets.chomp.split(",")
# TODO: totals = Hash.new(0); accumulate amount per category;
# then print categories with total >= 20, sorted by total desc
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier