Bird
0
0

Identify the error in this Ruby code that tries to set a default value of 0 for missing keys:

medium📝 Debug Q14 of 15
Ruby - Hashes
Identify the error in this Ruby code that tries to set a default value of 0 for missing keys:
h = Hash.new
h.default = 0
puts h[:missing]
Ah.default=0 sets default but does not affect missing keys
BNo error; code works and prints 0
Ch.default=0 should be h.default = 0 (space required)
DSyntax error in setting default value
Step-by-Step Solution
Solution:
  1. Step 1: Check default value assignment

    Using h.default = 0 correctly sets the default value for missing keys after hash creation.
  2. Step 2: Access missing key

    Accessing h[:missing] returns 0 as expected, no error occurs.
  3. Final Answer:

    No error; code works and prints 0 -> Option B
  4. Quick Check:

    Setting default after creation works [OK]
Quick Trick: Use h.default = value to set default after creation [OK]
Common Mistakes:
  • Thinking default= is a syntax error
  • Confusing default= with default_proc
  • Expecting missing keys to raise errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes