比较两个哈希值与键和值 - Ruby

时间:2013-03-19 15:02:33

标签: ruby ruby-on-rails-3.2

我有与本文中提到的相同的问题,但对于Ruby而不是Perl。 Comparing-two-hashes-with-the-keys-and-values - Perl

我想比较两个哈希值,首先查看它们是否存在于第一个哈希值中,是否存在于第二个哈希中,如果是,则比较值并打印哈希键的值,否则如果值不相等,打印具有不等值的键。

我看了很多建议,但找不到比较两个不同哈希值的答案。

2 个答案:

答案 0 :(得分:10)

h1 = {"a" => 1, "b" => 2, "c" => 3}
h2 = {"a" => 2, "b" => 2, "d" => 3}

(h1.keys & h2.keys).each {|k| puts ( h1[k] == h2[k] ? h1[k] : k ) }

输出:

a
2

答案 1 :(得分:6)

要查找客户端和事件数组中显示的所有人,我会收集这些值然后进行比较:

clients = {"address"=>"street.name.1" , "name"=>"john.doe" , "age"=>25} , {"address"=>"street.name2" , "name"=>"jane.doe" , "age"=>14} , {"address"=>"street.name.3" , "name"=>"tom.smith" , "age"=>35}
events = {"type"=>"party" , "participant"=>"lisa.cohen" , "date"=>"05.05.13"} , {"type"=>"corporate" , "participant"=>"john.doe" , "date"=>"26.05.13"} , {"type"=>"meeting" , "participant"=>"james.edwards" , "date"=>"14.05.13"}

#Get all client names
client_names = clients.collect{ |c| c['name'] }
p client_names
#=> ["john.doe", "jane.doe", "tom.smith"]

#Get all participant names
event_participants = events.collect{ |e| e['participant'] }
p event_participants
#=> ["lisa.cohen", "john.doe", "james.edwards"]

#Determine names that appear in both
names_in_both = client_names & event_participants
p names_in_both
#=> ["john.doe"]