0
0
Rubyprogramming~5 mins

Default values for missing keys in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ARaises an error for missing keys
BCreates a hash with one key 0
CReturns nil for missing keys
DReturns 0 for any missing key
How do you create a hash that assigns a new empty array for each missing key?
AHash.new([])
BHash.new { |h, k| h[k] = [] }
CHash.new(nil)
DHash.new(0)
What will this code output? h = Hash.new('default'); puts h[:missing].object_id == h[:another_missing].object_id
Anil
Bfalse
Ctrue
DError
Which method sets a default value only when a missing key is accessed and assigned?
Ahash[key] ||= default
BHash.new(default)
Chash.fetch(key, default)
Dhash.default = default
What is the default return value of a Ruby hash for a missing key if no default is set?
Anil
Bempty string
Cfalse
D0
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.