Join my Laravel for REST API's course on Udemy 👀

Merge hashes in Ruby

August 14, 2022  ‐ 2 min read

If we wish to merge two hashes together in Ruby we can make use of the .merge() and .merge!() methods. The former method returns a new hash object, the latter adds the contents of the given hash to the hash object on which the method is called.

Merging hashes wish .merge()

Since .merge() returns a new hash object, the original hashes are kept intact. Allowing us to reuse them at another place in our code.

hash1 = {a: 1, b: 2}
hash2 = {c: 3, d: 4}

merged = hash1.merge(hash2)
puts merged
puts hash1
#=> {:a=>1, :b=>2, :c=>3, :d=>4}
#=> {:a=>1, :b=>2}

Merging hashes wish .merge!()

.merge!() on the other hand mutates the hash on which we call the method, hash1 in this case. Thus, there is not really a point in assigning the return value to a new variable.

hash1 = {a: 1, b: 2}
hash2 = {c: 3, d: 4}

hash1.merge!(hash2)
puts hash1
#=> {:a=>1, :b=>2, :c=>3, :d=>4}

Duplicate keys

When we merge hashes with duplicate keys the value of the given hash is taken, not the hash on which we call the merge method. Both .merge() and .merge!() work in this manner.

hash1 = {hash: 'number one'}
hash2 = {hash: 'number two'}

result = hash1.merge(hash2)
puts result
#=> {:hash=>"number two"}