Introduction
Sometimes you want to get a value from a dictionary (hash) but the key might not be there. Default values help by giving you a safe answer instead of an error.
hash = Hash.new(default_value)h = Hash.new(0) h[:a] += 1 puts h[:a] puts h[:b]
h = Hash.new { |hash, key| hash[key] = [] } h[:a] << 1 puts h[:a].inspect puts h[:b].inspect
counts = Hash.new(0) words = ["apple", "banana", "apple", "orange", "banana", "apple"] words.each do |word| counts[word] += 1 end counts.each do |word, count| puts "#{word}: #{count}" end
h = Hash.new(0)Hash.new(0), it sets 0 as the default value for any missing key.Hash.new allows dynamic default values. To assign a new array to each missing key, the block must assign it to the hash.hash and key parameters and assigns [] to hash[key]. This ensures each missing key gets its own array.h = Hash.new { |hash, key| hash[key] = [] }
h[:a] << 1
h[:b] << 2
p hh[:a] creates :a => [1]. Similarly, appending 2 to h[:b] creates :b => [2].h = Hash.new h.default = 0 puts h[:missing]
h.default = 0 correctly sets the default value for missing keys after hash creation.h[:missing] returns 0 as expected, no error occurs.words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = ???
words.each { |w| counter[w] += 1 }
puts countercounter[w] += 1 works. The += reads the default 0, increments to 1, and assigns back, storing the key.Hash.new(0) returns 0 for missing keys (no store); += 1 stores the result. Perfect for counting.Hash.new { |h, k| [] } returns []; [] += 1 TypeError.Hash.new([]) returns shared []; TypeError.{} returns nil; error.Pass the test and this pattern moves unknown