ruby on rails - Find intersection of arrays of hashes by hash value -



ruby on rails - Find intersection of arrays of hashes by hash value -

if have 2 arrays of hashes 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 find intersection of these 2 arrays hashes id value?

so above illustration

intersection = <insert ruby code here> => [{id: 5678, name: "cheese stevens"}]

i can't utilize intersection = user1.connections & user2.connections because belongs_to_id different.

thanks!

simple that:

user1.connections & user2.connections

if want id key (other attributes different)

intersection = user1.connections.map{|oh| oh[:id]} & user1.connections.map{|oh| oh[:id]} user1.connections.select {|h| intersection .include? h[:id] }

hope helps!

ruby-on-rails ruby arrays hash intersection

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -