ruby-on-rails - 通过哈希值查找哈希数组的交集

标签 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 不同。

谢谢!

最佳答案

就这么简单:

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/

相关文章:

javascript - 在关联模型的 Ruby on Rails 表单中使用 Materialise `chip` 和 `autocomplete`

javascript - 有没有努力将一些 Rails 的 View Helpers 移植到 Javascript?

ruby-on-rails - 评估字符串模板

ruby-on-rails - 如何使用一张表格创建三条记录?以及如何显示它们的验证错误?

c - 输出是什么?请解释一下,考虑到我是c新手

Java集合排序和自定义排序-速度

ruby-on-rails - after_sign_in_path_for

ruby-on-rails - 在 JSON 中显示的未定义方法错误

ios - 在构建之前自动删除静态库以防止 Cocoapods 重复符号错误

c# - 在字符串 C# 中查找数组元素