If I have an 2 arrays of hashes for example:
user1.id
=> 1
user2.id
=> 2
user1.connections = [{id:1234, name: "Darth Vader", belongs_to_id: 1}, {id:5678, name: "Cheese Stevens", belongs_to_id: 1}]
user2.connections = [{id:5678, name: "Cheese Stevens", belongs_to_id: 2}, {id: 9999, "Blanch Albertson", belongs_to_id: 2}]
Then how in Ruby can I find the intersection of these two arrays by the hashes id value?
So that for the above example
intersection = <insert Ruby code here>
=> [{id: 5678, name: "Cheese Stevens"}]
I can't just use intersection = user1.connections & user2.connections
because the belongs_to_id is different.
Thanks!
simple as that:
user1.connections & user2.connections
if you want only by the id key (other attributes are different)
intersection = user1.connections.map{|oh| oh[:id]} & user2.connections.map{|oh| oh[:id]}
user1.connections.select {|h| intersection.include? h[:id] }
hope it helps!
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