How to merge multiple hashes in Ruby?

Since Ruby 2.0 on that can be accomplished more graciously:

h.merge **h1, **h2

And in case of overlapping keys - the latter ones, of course, take precedence:

h  = {}
h1 = { a: 1, b: 2 }
h2 = { a: 0, c: 3 }

h.merge **h1, **h2
# => {:a=>0, :b=>2, :c=>3}

h.merge **h2, **h1
# => {:a=>1, :c=>3, :b=>2}

You can just do

[*h,*h2,*h3].to_h
# => {:a=>1, :b=>2, :c=>3}

This works whether or not the keys are Symbols.


You could do it like this:

h, h2, h3  = { a: 1 }, { b: 2 }, { c: 3 }
a  = [h, h2, h3]

p Hash[*a.map(&:to_a).flatten] #= > {:a=>1, :b=>2, :c=>3}

Edit: This is probably the correct way to do it if you have many hashes:

a.inject{|tot, new| tot.merge(new)}
# or just
a.inject(&:merge)

Tags:

Ruby

Hash