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.
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"}
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