Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Hashes

What will be the output of the following Ruby code?

h1 = {x: 5, y: 10}
h2 = {y: 15, z: 20}
result = h1.merge(h2)
puts result
A{:x=>5, :y=>10, :z=>20}
B{:x=>5, :y=>15, :z=>20}
C{:x=>5, :y=>10}
D{:y=>15, :z=>20}
Step-by-Step Solution
Solution:
  1. Step 1: Understand merge behavior

    The merge method returns a new hash combining keys and values from both hashes.
  2. Step 2: Key conflicts resolution

    When keys overlap, values from the hash passed as argument (h2) overwrite those in the original (h1).
  3. Step 3: Resulting hash

    Keys :x, :y, and :z are present; :y's value is from h2 (15).
  4. Final Answer:

    {:x=>5, :y=>15, :z=>20} -> Option B
  5. Quick Check:

    Check overwritten keys and new keys [OK]
Quick Trick: merge returns new hash with argument's values overwriting [OK]
Common Mistakes:
  • Assuming original hash is modified
  • Ignoring that merge returns a new hash
  • Thinking values from original hash overwrite argument's

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes