How to merge multiple hashes?

14,754

Solution 1

You can do below way using Enumerable#inject:

h = {}
arr = [{:a=>"b"},{"c" => 2},{:a=>4,"c"=>"Hi"}]
arr.inject(h,:update)
# => {:a=>4, "c"=>"Hi"}
arr.inject(:update)
# => {:a=>4, "c"=>"Hi"}

Solution 2

How about:

[department_hash, super_saver_hash, categories_hash].reduce &:merge

Solution 3

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}
Share:
14,754
alexchenco
Author by

alexchenco

Programmer from Taiwan

Updated on June 13, 2022

Comments

  • alexchenco
    alexchenco about 2 years

    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?

  • Arup Rakshit
    Arup Rakshit almost 11 years
    why & ? [department_hash, super_saver_hash, categories_hash].reduce(:merge) is fine...
  • pguardiario
    pguardiario almost 11 years
    That's just my preference. I think the & informs something and is worthwhile.
  • Patrick Oscity
    Patrick Oscity almost 11 years
    @Babai because this style is consistent with e.g. Enumerable#map which requires a proc.
  • bigtunacan
    bigtunacan over 10 years
    I think the point is how would it be possible to do this with a single call. h1.merge(h2, h3) Obviously this does not actually work, but such behavior could be useful.
  • user1735921
    user1735921 over 7 years
    this is what I was looking for