Consider the following Ruby code that uses a hash with a default value. What will be printed?
h = Hash.new(0) h[:a] += 1 h[:b] += 2 puts h[:a] puts h[:b] puts h[:c]
Remember that the default value is returned for missing keys but does not get stored in the hash unless assigned.
The hash h is created with a default value of 0. When h[:a] += 1 runs, it reads the default 0, adds 1, and assigns 1 to :a. Similarly for :b. For :c, it was never assigned, so it returns the default 0.
What will this Ruby code print?
h = Hash.new { |hash, key| hash[key] = [] } h[:x] << 1 h[:y] << 2 puts h[:x].inspect puts h[:y].inspect puts h[:z].inspect
Using a block for default values allows the hash to assign a new object for missing keys.
The block sets the default value to a new empty array and assigns it to the missing key. So when h[:x] << 1 runs, it creates h[:x] = [] then appends 1. Same for :y. For :z, it creates an empty array assigned to :z.
Look at this Ruby code:
h = Hash.new([]) h[:a] << 1 h[:b] << 2 puts h[:a].inspect puts h[:b].inspect puts h.inspect
What is the output and why?
Think about whether the default object is shared or duplicated for each key.
Using Hash.new([]) sets the same array as the default object for all missing keys. So appending to h[:a] actually modifies the shared default array. The hash itself remains empty because no keys were assigned explicitly.
Which of the following Ruby hash initializations correctly sets a default value of 10 for missing keys?
Only one option assigns the default value to the key in the hash.
Option D uses a block that assigns 10 to the missing key, so the key is stored with value 10. Options A, B, and D return 10 as default but do not store it in the hash.
Given this Ruby code:
h = Hash.new { |hash, key| hash[key] = key * 2 }
h[1]
h[2]
h[3]
count = h.sizeWhat is the value of count after running this code?
Accessing a missing key with a block default assigns a value to that key.
Each time h[1], h[2], and h[3] is accessed, the block assigns key * 2 to that key in the hash. So after these three accesses, the hash has 3 keys.