我的情况:
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键)
答案 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}