Recall & Review
beginner
What happens when you access a missing key in a Ruby hash without a default value?
Ruby returns
nil when you access a key that does not exist in the hash and no default value is set.Click to reveal answer
beginner
How do you set a default value for missing keys in a Ruby hash?
You can set a default value by passing it when creating the hash, like
Hash.new(default_value). This value is returned for any missing key.Click to reveal answer
intermediate
What is the difference between
Hash.new(default_value) and hash[key] ||= default_value?Hash.new(default_value) sets a default for all missing keys automatically. hash[key] ||= default_value sets the value only when you access a missing key and want to assign a default at that moment.Click to reveal answer
intermediate
How can you use a block to set default values dynamically in a Ruby hash?
You can create a hash with a block like
Hash.new { |hash, key| hash[key] = some_value }. This block runs when a missing key is accessed, allowing dynamic default values.Click to reveal answer
advanced
Why might using a mutable object as a default value cause unexpected behavior?
If you use a mutable object (like an array) as a default value, the same object is shared for all missing keys, so changes affect all keys. Using a block to create a new object each time avoids this.
Click to reveal answer
What does
Hash.new(0) do in Ruby?✗ Incorrect
Using
Hash.new(0) sets the default value to 0, so any missing key returns 0.How do you create a hash that assigns a new empty array for each missing key?
✗ Incorrect
Using a block with
Hash.new { |h, k| h[k] = [] } creates a new array for each missing key, avoiding shared mutable objects.What will this code output?
h = Hash.new('default'); puts h[:missing].object_id == h[:another_missing].object_id✗ Incorrect
The default object is shared, so both missing keys return the same object, making their object_ids equal.
Which method sets a default value only when a missing key is accessed and assigned?
✗ Incorrect
hash[key] ||= default assigns the default value only if the key is missing or falsey.What is the default return value of a Ruby hash for a missing key if no default is set?
✗ Incorrect
By default, Ruby hashes return
nil for keys that do not exist.Explain how to set and use default values for missing keys in a Ruby hash.
Think about how Ruby handles missing keys and how you can customize that.
You got /4 concepts.
Describe why using a mutable object as a default value can cause problems and how to avoid it.
Consider what happens if you change the default object.
You got /4 concepts.