Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two hashes with the keys and values - Ruby

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.

like image 374
stephiepea Avatar asked Mar 19 '13 15:03

stephiepea


2 Answers

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
like image 191
Yuri Golobokov Avatar answered Oct 04 '22 10:10

Yuri Golobokov


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"]
like image 45
Justin Ko Avatar answered Oct 04 '22 12:10

Justin Ko