0
0
Rubyprogramming~10 mins

Merge and update methods in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to merge two hashes using the merge method.

Ruby
hash1 = {a: 1, b: 2}
hash2 = {b: 3, c: 4}
result = hash1.[1](hash2)
puts result
Drag options to blanks, or click blank then click option'
Aupdate
Bcombine
Cmerge
Dconcat
Attempts:
3 left
💡 Hint
Common Mistakes
Using update instead of merge changes the original hash.
2fill in blank
medium

Complete the code to update a hash with another hash using the update method.

Ruby
hash1 = {x: 10, y: 20}
hash2 = {y: 30, z: 40}
hash1.[1](hash2)
puts hash1
Drag options to blanks, or click blank then click option'
Aupdate
Bmerge
Creplace
Dconcat
Attempts:
3 left
💡 Hint
Common Mistakes
Using merge instead of update does not change the original hash.
3fill in blank
hard

Fix the error in the code to correctly merge two hashes with a block to handle conflicts.

Ruby
h1 = {a: 100, b: 200}
h2 = {b: 254, c: 300}
result = h1.merge(h2) { |key, old_val, new_val| [1] }
puts result
Drag options to blanks, or click blank then click option'
Aold_val * new_val
Bold_val - new_val
Cnew_val - old_val
Dold_val + new_val
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication changes the intended result.
4fill in blank
hard

Fill both blanks to create a hash comprehension that merges two hashes and keeps the larger value for duplicate keys.

Ruby
h1 = {a: 5, b: 10}
h2 = {b: 7, c: 12}
result = h1.merge(h2) { |[1], old_val, new_val| old_val [2] new_val ? old_val : new_val }
puts result
Drag options to blanks, or click blank then click option'
Akey
Bk
Cx
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names or comparison operators.
5fill in blank
hard

Fill all three blanks to update a hash with another hash, but keep the original value if the new value is nil.

Ruby
h1 = {a: 1, b: 2}
h2 = {b: nil, c: 3}
h1.update(h2) { |[1], old_val, new_val| new_val [2] nil ? new_val : [3] }
puts h1
Drag options to blanks, or click blank then click option'
Akey
B!=
Cold_val
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of != causes wrong logic.
Returning new_val when it is nil replaces original value incorrectly.