Challenge - 5 Problems
Ruby Hash Merge Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using merge?
Consider the following Ruby code snippet. What will be printed?
Ruby
h1 = {a: 1, b: 2}
h2 = {b: 3, c: 4}
result = h1.merge(h2)
puts resultAttempts:
2 left
💡 Hint
Remember that merge returns a new hash with keys from both hashes, and values from the second hash overwrite the first.
✗ Incorrect
The merge method combines two hashes. When keys overlap, the value from the second hash replaces the first. Here, :b is overwritten from 2 to 3.
❓ Predict Output
intermediate2:00remaining
What does update do to the original hash?
Given this Ruby code, what will be the value of h1 after update?
Ruby
h1 = {x: 10, y: 20}
h2 = {y: 30, z: 40}
h1.update(h2)
puts h1Attempts:
2 left
💡 Hint
Update modifies the original hash by adding or replacing keys from the argument hash.
✗ Incorrect
The update method changes h1 in place, adding :z and replacing :y with 30.
🔧 Debug
advanced2:00remaining
Why does this merge code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
h1 = {a: 1, b: 2}
h2 = nil
h1.merge(h2)Attempts:
2 left
💡 Hint
Check what merge expects as an argument and what nil is.
✗ Incorrect
merge expects a hash or something convertible to a hash. nil does not respond to to_hash, causing NoMethodError.
❓ Predict Output
advanced2:00remaining
What is the output when using merge with a block?
What will this Ruby code print?
Ruby
h1 = {a: 100, b: 200}
h2 = {b: 300, c: 400}
result = h1.merge(h2) { |key, old_val, new_val| old_val + new_val }
puts resultAttempts:
2 left
💡 Hint
The block tells merge how to combine values for duplicate keys.
✗ Incorrect
For key :b, the block adds old and new values: 200 + 300 = 500. Other keys are merged normally.
🧠 Conceptual
expert3:00remaining
How many keys are in the hash after this update?
Given this Ruby code, how many keys does h1 have after update?
Ruby
h1 = {a: 1, b: 2, c: 3}
h2 = {b: 4, d: 5, e: 6}
h1.update(h2)
h1.delete(:c)
h1[:f] = 7
puts h1.keys.sizeAttempts:
2 left
💡 Hint
Count keys after update, delete, and adding a new key.
✗ Incorrect
After update, h1 has keys :a, :b, :c, :d, :e. Then :c is deleted, leaving 4 keys. Adding :f makes 5 keys total.