Bird
0
0

Fix the error in this Ruby code that tries to assign a unique array to each missing key:

medium📝 Debug Q7 of 15
Ruby - Hashes
Fix the error in this Ruby code that tries to assign a unique array to each missing key:
h = Hash.new([])
h[:a] << 1
puts h[:a].inspect
AChange to h = Hash.new({})
BUse Hash.new { |hash, key| hash[key] = [] } instead
CAssign h.default = [] after creation
DUse h = Hash.new(nil) and check for nil
Step-by-Step Solution
Solution:
  1. Step 1: Identify problem with shared default array

    Using Hash.new([]) shares the same array for all missing keys.
  2. Step 2: Use block to assign unique array per key

    Hash.new { |hash, key| hash[key] = [] } creates a new array for each missing key.
  3. Final Answer:

    Use Hash.new { |hash, key| hash[key] = [] } instead -> Option B
  4. Quick Check:

    Block default creates unique objects per key [OK]
Quick Trick: Use block with hash default for unique objects per key [OK]
Common Mistakes:
  • Using shared default object
  • Assigning default after creation incorrectly
  • Confusing default with nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes