Home > Enterprise >  Ruby - Merging two hashes with some keys similar
Ruby - Merging two hashes with some keys similar

Time:10-11

Essentially I only want to merge the keys which appear in both hashes. the end goal is adding or multiplying the values.

hash1 = {"a" => 1, "b" => 2, "c" => 3 }
hash2 = {"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5}
{"a" => 2, "b" => 4, "c" => 6 }

This worked in a sense of adding the correct values, however also returned d and e.

hash1.merge(hash2) { |key1, value1, value2| value1   value2 }
#=> {"a" => 2, "b" => 4, "c" => 6, "d" => 4, "e" => 5}

CodePudding user response:

Try below code

hash1 = {"a" => 1, "b" => 2, "c" => 3 }
hash2 = {"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5}


(hash1.keys & hash2.keys).map{ |key| [key, hash1[key]   hash2[key]]}.to_h
 => {"a"=>2, "b"=>4, "c"=>6} 

CodePudding user response:

You could determine the common keys via &:

keys = hash1.keys & hash2.keys
#=> ["a", "b", "c"]

and then use slice before merge:

hash1.slice(*keys).merge(hash2.slice(*keys)) { |k, v1, v2| v1   v2 }
#=> {"a"=>2, "b"=>4, "c"=>6}

In your example, the result is equivalent to merging the keys from hash2 that also exist in hash1 which could be written as:

hash1.merge(hash2.slice(*hash1.keys)) { |k, v1, v2| v1   v2 }
#=> {"a"=>2, "b"=>4, "c"=>6}

This however only works if hash1 defines the common keys.

  • Related