Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Hashes
What is the output of this Ruby code?
h = Hash.new("missing")
h[:a] = 1
puts h[:a]
puts h[:b]
Anil missing
B1 nil
Cmissing missing
D1 missing
Step-by-Step Solution
Solution:
  1. Step 1: Analyze hash creation and assignments

    The hash h has default value "missing". Key :a is assigned 1.
  2. Step 2: Check outputs for keys :a and :b

    h[:a] returns 1 because it exists. h[:b] does not exist, so returns default "missing".
  3. Final Answer:

    1\nmissing -> Option D
  4. Quick Check:

    Existing key returns value; missing returns default [OK]
Quick Trick: Existing keys return value; missing keys return default [OK]
Common Mistakes:
  • Assuming missing keys return nil
  • Confusing default value with key value
  • Expecting error on missing key

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes