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

前端之家收集整理的这篇文章主要介绍了比较两个哈希值与键和值 – Ruby前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有与本文中提到的相同的问题,但对于 Ruby而不是Perl.
Comparing-two-hashes-with-the-keys-and-values – Perl

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

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

解决方法

要查找在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"]
原文链接:https://www.f2er.com/ruby/269183.html

猜你在找的Ruby相关文章