Ayush Mittal
Ayush Mittal

Reputation: 11

Ruby: Merging two hashes based on keys from one hash

I have two hashes

hash1 = {"a" => { "b" => {}, "c" => {}} , "d" => { "e" => {} } }

hash2 = {"a" => { "b" => {"x" => "y"}, "z" => 1}}

Now I want the merge to be in such a way that all the keys from hash1 are present in the final hash, and the value if present in the second hash should get merged and anything which is not there in hash1 should be removed.

So the output of this should be

final_hash = {"a" => { "b" => {"x" => "y"}, "c" => {}} , "d" => { "e" => {} } }

Upvotes: 0

Views: 280

Answers (1)

Peter Camilleri
Peter Camilleri

Reputation: 1902

I came up with the following, not pretty but here it is:

require 'pp'

hash1 = {"a" => {"b" => {}, "c" => {}}, "d" => {"e" => {}}}
hash2 = {"a" => {"b" => {"x" => "y"}, "z" => 1}}

final_hash = {"a" => {"b" => {"x" => "y"}, "c" => {}}, "d" => {"e" => {}}}

puts
pp hash1
pp hash2

class Hash

  def mittal_merge(source)
    result = {}

    keys.each do |key|
      value = {}

      self[key].keys.each do |sub_key|
        value[sub_key] = (source[key] || {})[sub_key] || {}
      end

      result[key] = value
    end

    result
  end


end

puts
pp final_hash
pp hash1.mittal_merge(hash2)

and here is the result:

{"a"=>{"b"=>{}, "c"=>{}}, "d"=>{"e"=>{}}}
{"a"=>{"b"=>{"x"=>"y"}, "z"=>1}}

{"a"=>{"b"=>{"x"=>"y"}, "c"=>{}}, "d"=>{"e"=>{}}}
{"a"=>{"b"=>{"x"=>"y"}, "c"=>{}}, "d"=>{"e"=>{}}}

Upvotes: 1

Related Questions