例如,如果我有两个散列数组:
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是不同的。
谢谢!
发布于 2014-06-18 22:12:47
很简单:
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] }希望能帮上忙!
https://stackoverflow.com/questions/24295763
复制相似问题