How to merge hashes in Ruby

Overview

We can merge two hashes using the merge() method. When using the merge() method:

  • Each new entry is added to the end.
  • Each duplicate-key entry’s value overwrites the previous value.

Syntax

hash.merge(other_hash)

Parameter(s)

other_hash: This is the hash we want to merge with the hash. They could be one or more.

Return value

This method returns a new hash object formed by merging other_hash into hash hash.

Example

# create some hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {two:22, three: 33}
h3 = {"foo": 0, "bar": 1}
h4 = {"foo": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
h5 = {C: "Cabbage", P: "Pineapple"}
# merge hashes
puts h1.merge(h2)
puts h3.merge(h4)
puts h4.merge(h5)

Explanation

  • Lines 2 to 7: We create some hashes.
  • Lines 10 to 12: We merge some hashes and their results are printed to the console.

Free Resources