I have the same question as was asked in this post, but for Ruby instead of Perl. Comparing-two-hashes-with-the-keys-and-values - Perl
I want to compare two hashes, first to see if they key which is in the 1st hash, exists in the 2nd hash and if so compare the values and print the value of the hash key else if the values are not equal, print the key which has the unequal value.
I have looked at many suggestions, but cannot find an answer for comparing values in two different hashes.
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 ) }
Output:
a
2
To find all people displayed in both the clients and events array, I would collect the values and then compare them:
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With