How To Merge Two Hashes In Ruby

In this blog post, we will learn how to merge two hashes in Ruby. Hashes are a fundamental data structure in Ruby,
and merging them is an essential operation you might need in many real-world scenarios.

Using the merge method

The simplest way to merge two hashes in Ruby is to use the built-in merge method. The merge
method takes another hash as an argument and returns a new hash that is a combination of the two. If there are any
conflicting keys, the values from the second hash will overwrite the values from the first.

Here’s an example of how to use the merge method:

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

    merged_hash = hash1.merge(hash2)
    puts merged_hash.inspect
    # Output: {:a=>1, :b=>4, :c=>5, :d=>6}
    

Note that the original hashes are not modified:

    puts hash1.inspect
    # Output: {:a=>1, :b=>2, :c=>3}

    puts hash2.inspect
    # Output: {:b=>4, :c=>5, :d=>6}
    

Using the merge! method

If you want to modify the first hash in place, you can use the merge! method. This method works
similarly to the merge method, but it updates the first hash with the merged values:

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

    hash1.merge!(hash2)
    puts hash1.inspect
    # Output: {:a=>1, :b=>4, :c=>5, :d=>6}
    

Merging with a custom logic

You might want to merge two hashes with a custom logic to resolve conflicts. In this case, you can provide a block
to the merge or merge! methods. The block takes three arguments: the key, the value
from the first hash, and the value from the second hash. The return value of the block determines the final value
for that key:

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

    custom_merged_hash = hash1.merge(hash2) do |key, value1, value2|
      value1 + value2
    end
    puts custom_merged_hash.inspect
    # Output: {:a=>1, :b=>6, :c=>8, :d=>6}
    

Conclusion

In this blog post, we’ve learned how to merge two hashes in Ruby using the merge and
merge! methods. We’ve also explored how to use a custom logic for merging by providing a block.
Merging hashes is an essential operation, and understanding how to use these methods will make your code more
efficient and readable.