0
0
Rubyprogramming~20 mins

Merge and update methods in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Hash Merge Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 result
A{:a=>1, :b=>2}
B{:a=>1, :b=>3, :c=>4}
C{:a=>1, :b=>3}
D{:a=>1, :b=>2, :c=>4}
Attempts:
2 left
💡 Hint
Remember that merge returns a new hash with keys from both hashes, and values from the second hash overwrite the first.
Predict Output
intermediate
2: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 h1
A{:x=>10, :y=>30}
B{:x=>10, :y=>20, :z=>40}
C{:x=>10, :y=>20}
D{:x=>10, :y=>30, :z=>40}
Attempts:
2 left
💡 Hint
Update modifies the original hash by adding or replacing keys from the argument hash.
🔧 Debug
advanced
2: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)
ANoMethodError because nil does not have to_hash method
BArgumentError because merge expects a hash argument
CTypeError because nil cannot be merged
DSyntaxError due to invalid syntax
Attempts:
2 left
💡 Hint
Check what merge expects as an argument and what nil is.
Predict Output
advanced
2: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 result
A{:a=>100, :b=>500, :c=>400}
B{:a=>100, :b=>300, :c=>400}
C{:a=>100, :b=>200, :c=>400}
D{:a=>100, :b=>200, :c=>300}
Attempts:
2 left
💡 Hint
The block tells merge how to combine values for duplicate keys.
🧠 Conceptual
expert
3: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.size
A6
B4
C5
D3
Attempts:
2 left
💡 Hint
Count keys after update, delete, and adding a new key.