通过哈希值查找哈希数组的交集

时间:2014-06-18 22:06:00

标签: ruby-on-rails ruby arrays hash intersection

如果我有2个哈希数组,例如:

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}]

然后在Ruby中如何通过哈希id值找到这两个数组的交集?

所以对于上面的例子

intersection = <insert Ruby code here>
=> [{id: 5678, name: "Cheese Stevens"}]

我不能只使用intersection = user1.connections & user2.connections因为belongs_to_id不同。

谢谢!

1 个答案:

答案 0 :(得分:4)

简单:

user1.connections & user2.connections

如果你只想通过id键(其他属性不同)

intersection = user1.connections.map{|oh| oh[:id]} & user2.connections.map{|oh| oh[:id]}
user1.connections.select {|h| intersection.include? h[:id] }
希望它有所帮助!