Menu
Coddy logo textTech

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"]   # nil

Hash.new(default) changes that. Every missing key returns the value you passed in:

scores = Hash.new(0)
puts scores["Alice"]   # 0

This 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 icon

Challenge

Easy

Read 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: 20

If 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"]   # 0

This 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow