[英]Find intersection of arrays of hashes by hash value
如果我有一个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是不同的。
谢谢!
就那么简单:
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] }
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.