你如何比较两个哈希中的元素

时间:2012-05-24 20:57:17

标签: ruby

我希望比较两个哈希来确定哪些值可以匹配。例如:

hash1 = {
    "hash1_key_a" => 1,
    "hash1_key_b" => 2
}

hash2 = {
    "hash2_key_a" => 1,
    "hash2_key_b" => 3,
    "hash2_key_c" => 4
}

# The method here should display the matching keys & values,
# and then delete them from their hashes. For example:

puts "#{hash1_key_a};#{hash2_key_a};1" # 1 is representing the referral we should
                                       # put in for the value

有人能引导我朝正确的方向前进吗?

1 个答案:

答案 0 :(得分:0)

哈希是否有不同的键?然后你可以做这样的事情:

hash1.merge(hash2).group_by{|k,v| v}.each{ |v,ks|
   puts "#{ ks.map(&:first)*';' };#{ v }"
}