比较两个哈希值并创建新哈希值或使用新键/值更改现有哈希值

时间:2014-08-19 16:50:48

标签: ruby hash

我的情况:

hash1 = {
       "344"=> "QTC-2",
       "343"=> "QTC-1"
       }

hash2 =  {
        "QTC-1"=> 1,
        "QTC-2"=> 1,
        "QTC-3"=> 2
       }

我想比较hash1和hash2。我想循环哈希并且:

如果hash1值与hash2键(QTC-1 == QTC-1)匹配,则新哈希应该变为:

new_hash3 = {
          "344"=> '1',
          "343"=> '1'
        }

(或更改hash1值而不是制作new_hash3或更改hash2键)

1 个答案:

答案 0 :(得分:3)

hash1 = {"344"=>"QTC-2", "343"=>"QTC-1"}
hash2 = {"QTC-1"=> 1, "QTC-2"=> 1, "QTC-3"=> 2 }


new_hash3 = hash1.each_with_object({}) {|(k,v), h| h[k] = hash2[v] if hash2.has_key?(v) }
# => {"344"=>1, "343"=>1}