mharris7190 mharris7190 - 4 months ago 16
Ruby Question

Find intersection of arrays of hashes by hash value

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!

Answer

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!