Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: compare two hashes [closed]

I have two hashes-

hash1 = {a: "2", b: "34", c: "53", d: "23", e: "2"}
hash2 = {a: "5", c: "8", d: "3", e: "2", f: "76"}

I need compare hashes and get next-

hash1_1 = {a: "2", c: "53", d: "23", e: "2"}
hash2_1 = {a: "5", c: "8", d: "3", e: "2"}

That is, I need to compare two hash and leave them only those values ​​whose keys are equal and there are both hashes.

like image 832
Vasia Pupkin Avatar asked Dec 20 '25 19:12

Vasia Pupkin


1 Answers

I would do as below :

hash1 = {a: "2", b: "34", c: "53", d: "23", e: "2"}
hash2 = {a: "5", c: "8", d: "3", e: "2", f: "76"}

hash1_1 = hash1.select{|k,_| hash2.has_key? k} 
# => {:a=>"2", :c=>"53", :d=>"23", :e=>"2"}
hash1_2 = hash2.select{|k,_| hash1.has_key? k}
# => {:a=>"5", :c=>"8", :d=>"3", :e=>"2"}
like image 87
Arup Rakshit Avatar answered Dec 22 '25 09:12

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!