8

我的问题与这篇文章中提出的问题相同,但针对的是 Ruby 而不是 Perl。 比较两个哈希与键和值 - Perl

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

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

4

2 回答 2

12
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
于 2013-03-19T15:14:42.483 回答
7

要查找显示在 clients 和 events 数组中的所有人,我会收集这些值然后比较它们:

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"]
于 2013-03-19T16:47:05.667 回答