0
0
Rubyprogramming~5 mins

Merge and update methods in Ruby

Choose your learning style9 modes available
Introduction

Merge and update methods help you combine two sets of information into one. They make it easy to add or change data in a hash (a collection of key-value pairs).

You want to combine two lists of settings into one.
You need to add new information to an existing collection without losing old data.
You want to change some values in a collection based on new input.
You want to create a new combined collection without changing the original.
You want to update the original collection directly with new data.
Syntax
Ruby
hash1.merge(hash2)  # returns a new hash with combined keys and values
hash1.merge!(hash2) # updates hash1 with hash2's keys and values

hash1.update(hash2) # same as merge! - updates hash1 with hash2

merge returns a new hash and does not change the original.

merge! and update change the original hash directly.

Examples
This creates a new hash combining h1 and h2. If keys overlap, h2's values are used.
Ruby
h1 = {a: 1, b: 2}
h2 = {b: 3, c: 4}
new_hash = h1.merge(h2)
puts new_hash
This changes h1 by adding h2's keys and values. Overlapping keys get updated.
Ruby
h1 = {a: 1, b: 2}
h2 = {b: 3, c: 4}
h1.merge!(h2)
puts h1
update works like merge! and changes h1 directly.
Ruby
h1 = {a: 1, b: 2}
h2 = {b: 3, c: 4}
h1.update(h2)
puts h1
Sample Program

This program shows how merge creates a new combined hash without changing the original, while update changes the original hash directly.

Ruby
settings = {volume: 5, brightness: 7}
new_settings = {brightness: 10, contrast: 3}

# Using merge to create a new hash
combined = settings.merge(new_settings)
puts "Combined settings: #{combined}"

# Original settings stay the same
puts "Original settings: #{settings}"

# Using update to change original
settings.update(new_settings)
puts "Updated original settings: #{settings}"
OutputSuccess
Important Notes

If keys overlap, the values from the second hash replace those in the first.

Use merge when you want to keep the original hash unchanged.

Use merge! or update when you want to change the original hash.

Summary

merge returns a new hash combining two hashes.

merge! and update change the original hash.

Overlapping keys get their values replaced by the second hash.