h = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }
Hash#merge works for 2 hashes: h.merge(h2)
How to merge 3 hashes?
h.merge(h2).merge(h3)
works but is there a better way?
Join Stack Overflow to learn, share knowledge, and build your career.
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)
array.reduce(&:merge)
is going to give you the same result as inject
(inject
is just an alias of reduce
)
– ocodo
May 28 '14 at 9:20
Hash[]
will accept a series of arguments and build a hash by pairing them up. As such, if you generate an ordered array from the hashes (via a.map(&:to_a).flatten
) and use the splat operator to pass them as args, it will work nicely. However, Hash[]
also accepts an array of 2-ary arrays representing k-v pairs and I would have written it as Hash[*a.flat_map(&:to_a)]
– Brennan
Feb 22 '19 at 3:03
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}
h1
and h2
are {}
. It'll raise and error. h.merge(**{}, **{})
– tiagomenegaz
Mar 22 '19 at 19:29
You can just do
[*h,*h2,*h3].to_h
# => {:a=>1, :b=>2, :c=>3}
This works whether or not the keys are Symbol
s.
Ruby 2.6 allows merge
to take multiple arguments:
h = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }
h4 = { 'c' => 4 }
h5 = {}
h.merge(h2, h3, h4, h5) # => {:a=>1, :b=>2, :c=>3, "c"=>4}
This works with Hash.merge!
and Hash.update
too. Docs for this here.
Also takes empty hashes and keys as symbols or strings.
Much simpler :)
reduce
(same as inject
)hash_arr = [{foo: "bar"}, {foo2: "bar2"}, {foo2: "bar2b", foo3: "bar3"}]
hash_arr.reduce { |acc, h| (acc || {}).merge h }
# => {:foo2=>"bar2", :foo3=>"bar3", :foo=>"bar"}
For those beginning with Ruby or functional programming, I hope this brief explanation might help understand what's happening here.
The reduce
method when called on an Array object (hash_arr
) will iterate through each element of the array with the returned value of the block being stored in an accumulator (acc
). Effectively, the h
parameter of my block will take on the value of each hash in the array, and the acc
parameter will take on the value that is returned by the block through each iteration.
We use (acc || {})
to handle the initial condition where acc
is nil. Note that the merge
method gives priority to keys/values in the original hash. This is why the value of "bar2b"
doesn't appear in my final hash.
Hope that helps!
reduce
and inject
the accumulator (or memo) is passed as the initial argument to the block rather than the final argument as this suggests (unlike each_with_object
)
– engineersmnky
Mar 30 '18 at 2:53
To build upon @Oleg Afanasyev's answer, you can also do this neat trick:
h = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }
z = { **h, **h2, **h3 } # => {:a=>1, :b=>2, :c=>3}
Cheers!
class Hash
def multi_merge(*args)
args.unshift(self)
args.inject { |accum, ele| accum.merge(ele) }
end
end
That should do it. You could easily monkeypatch that into Hash as I have shown.
newHash = [h, h2, h3].each_with_object({}) { |oh, nh| nh.merge!(oh)}
# => {:a=>1, :b=>2, :c=>3}
#merge!
instead of #merge
. #merge
, alias #update
, is significantly faster in this case.
– Boris Stitnicky
Oct 27 '13 at 23:48
Here are the 2 monkeypatched ::Hash instance methods we use in our app. Backed by Minitest specs. They use merge!
instead of merge
internally, for performance reasons.
class ::Hash
# Merges multiple Hashes together. Similar to JS Object.assign.
# Returns merged hash without modifying the receiver.
#
# @param *other_hashes [Hash]
#
# @return [Hash]
def merge_multiple(*other_hashes)
other_hashes.each_with_object(self.dup) do |other_hash, new_hash|
new_hash.merge!(other_hash)
end
end
# Merges multiple Hashes together. Similar to JS Object.assign.
# Modifies the receiving hash.
# Returns self.
#
# @param *other_hashes [Hash]
#
# @return [Hash]
def merge_multiple!(*other_hashes)
other_hashes.each(&method(:merge!))
self
end
end
Tests:
describe "#merge_multiple and #merge_multiple!" do
let(:hash1) {{
:a => "a",
:b => "b"
}}
let(:hash2) {{
:b => "y",
:c => "c"
}}
let(:hash3) {{
:d => "d"
}}
let(:merged) {{
:a => "a",
:b => "y",
:c => "c",
:d => "d"
}}
describe "#merge_multiple" do
subject { hash1.merge_multiple(hash2, hash3) }
it "should merge three hashes properly" do
assert_equal(merged, subject)
end
it "shouldn't modify the receiver" do
refute_changes(->{ hash1 }) do
subject
end
end
end
describe "#merge_multiple!" do
subject { hash1.merge_multiple!(hash2, hash3) }
it "should merge three hashes properly" do
assert_equal(merged, subject)
end
it "shouldn't modify the receiver" do
assert_changes(->{ hash1 }, :to => merged) do
subject
end
end
end
end
Just for fun, you can do it also this way:
a = { a: 1 }, { b: 2 }, { c: 3 }
{}.tap { |h| a.each &h.method( :update ) }
#=> {:a=>1, :b=>2, :c=>3}
merge
can take multiple hashes as arguments. More info here. – SRack Nov 16 '18 at 17:28