how to get the key and value from two hashes (if their key matches) in a third hash

advertisements

Suppose i have two hashes say

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

hash2 = {2=>"whats" ,4 =>"up" ,5=> "dude"}

and i have to create a resultant hash such that if their keys matches then resultant hash must contain key (which is the the value in 1st hash) and value (which is the value corresponding matched key)

hash3 ={b=>"whats" ,d=>"up"}


This construct may be a little cryptic but it also does the job.

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

hash3 = Hash[(hash1.keys & hash2.keys).map do |k|
  [hash1[k], hash2[k]]
end]
hash3 # => {"b"=>"whats", "d"=>"up"}

Another way

hash3 = hash2.each_with_object({}) do |(k, v), memo|
  memo[hash1[k]] = v if hash1[k]
end
hash3 # => {"b"=>"whats", "d"=>"up"}