mha*_*190 5 ruby arrays hash intersection ruby-on-rails
例如,如果我有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}]
Run Code Online (Sandbox Code Playgroud)
那么在Ruby中如何通过哈希ID值找到这两个数组的交集?
所以对于上面的例子
intersection = <insert Ruby code here>
=> [{id: 5678, name: "Cheese Stevens"}]
Run Code Online (Sandbox Code Playgroud)
我不能只使用,intersection = user1.connections & user2.connections因为belongs_to_id不同。
谢谢!
就那么简单:
user1.connections & user2.connections
Run Code Online (Sandbox Code Playgroud)
如果你只想通过 id 键(其他属性不同)
intersection = user1.connections.map{|oh| oh[:id]} & user2.connections.map{|oh| oh[:id]}
user1.connections.select {|h| intersection.include? h[:id] }
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
1416 次 |
| 最近记录: |