Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Hashes
What is the output of the following Ruby code?
h = Hash.new { |hash, key| hash[key] = [] }
h[:a] << 1
h[:b] << 2
p h
A{:a=>[1], :b=>[2], :c=>[]}
B{:a=>[1], :b=>[2], nil=>[]}
C{:a=>[1], :b=>[2]}
D{}
Step-by-Step Solution
Solution:
  1. Step 1: Understand default block behavior

    The hash is created with a block that assigns an empty array to missing keys when accessed.
  2. Step 2: Modify arrays for keys :a and :b

    Appending 1 to h[:a] creates :a => [1]. Similarly, appending 2 to h[:b] creates :b => [2].
  3. Step 3: Print the hash

    Only keys :a and :b have values. No other keys exist.
  4. Final Answer:

    {:a=>[1], :b=>[2]} -> Option C
  5. Quick Check:

    Default arrays assigned and modified correctly [OK]
Quick Trick: Default block assigns new array per missing key [OK]
Common Mistakes:
  • Expecting keys not accessed to appear
  • Confusing default value with nil
  • Thinking default array is shared

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes