Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple hashes?

Tags:

ruby

hash

Right now, I'm merging two hashes like this:

department_hash  = self.parse_department html
super_saver_hash = self.parse_super_saver html

final_hash = department_hash.merge(super_saver_hash)

Output:

{:department=>{"Pet Supplies"=>{"Birds"=>16281, "Cats"=>245512, "Dogs"=>513926, "Fish & Aquatic Pets"=>46811, "Horses"=>14805, "Insects"=>364, "Reptiles & Amphibians"=>5816, "Small Animals"=>19769}}, :super_saver=>{"Free Super Saver Shipping"=>126649}}

But now I want to merge more in the future. For example:

department_hash  = self.parse_department html
super_saver_hash = self.parse_super_saver html
categories_hash  = self.parse_categories html

How to merge multiple hashes?

like image 980
alexchenco Avatar asked Aug 20 '13 07:08

alexchenco


People also ask

How do you combine hashes?

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.


2 Answers

How about:

[department_hash, super_saver_hash, categories_hash].reduce &:merge
like image 162
pguardiario Avatar answered Sep 20 '22 16:09

pguardiario


You can just call merge again:

h1 = {foo: :bar}
h2 = {baz: :qux}
h3 = {quux: :garply}

h1.merge(h2).merge(h3)
#=> {:foo=>:bar, :baz=>:qux, :quux=>:garply}
like image 31
Stefan Avatar answered Sep 18 '22 16:09

Stefan