Bird
0
0

How do you create a Ruby hash that automatically assigns a new empty array to any missing key and stores it in the hash?

hard📝 Application Q9 of 15
Ruby - Hashes
How do you create a Ruby hash that automatically assigns a new empty array to any missing key and stores it in the hash?
Ah = Hash.new { |hash, key| hash[key] = [] }
Bh = Hash.new([])
Ch = Hash.new([]); h.default = []
Dh = Hash.new { [] }
Step-by-Step Solution
Solution:
  1. Step 1: Use block with Hash.new

    Using a block allows assigning a new array for each missing key.
  2. Step 2: Assign new array to missing key

    The block sets hash[key] = [], storing the new array in the hash.
  3. Final Answer:

    h = Hash.new { |hash, key| hash[key] = [] } -> Option A
  4. Quick Check:

    Accessing missing keys returns unique arrays stored in hash [OK]
Quick Trick: Use block to assign new object per missing key [OK]
Common Mistakes:
MISTAKES
  • Using Hash.new([]) which shares the same array for all keys
  • Setting default after creation without block, causing shared object
  • Using block without assigning to hash[key], so values not stored

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes