例如,如果我有 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] }
希望对您有所帮助!
关于ruby-on-rails - 通过哈希值查找哈希数组的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295763/