mharris7190 mharris7190 - 1 year ago 108
Ruby Question

Find intersection of arrays of hashes by hash value

If I have an 2 arrays of hashes for example:
=> 1
=> 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.


Answer Source

simple as that:

user1.connections & user2.connections

if you want only by the id key (other attributes are different)

intersection ={|oh| oh[:id]} &{|oh| oh[:id]} {|h| intersection.include? h[:id] }

hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download