arrays - 根据属性对两个数组进行交集后返回对象
问题描述
我有两个数组,都填充了具有许多属性的对象。两个数组都持有相同的对象类型。我想根据对象的属性查找对象匹配的位置id
对象示例:
#<Link:0x00007fac5eb6afc8 @id = 2002001, @length=40, @area='mars' ...>
用对象填充的示例数组:
array_links = [<Link:0x00007fac5eb6afc8>, <Link:0x00007fdf5eb7afc2>, <Link:0x000081dag6zb7agg8>... ]
selected_links = [<Link:0x00007fad8ob6gbh5>, <Link:0x00007fdg7hh4tif4>, <Link:0x000081dag7ij5bhh9>... ]
如果这些是对象 ID 的字符串并且存在匹配项,我可以使用:
intersection = array_links & selected_links
但是,我想根据它们的属性执行此操作并返回匹配的对象本身。就像是:
intersection = array_links.select(&:id) & selected_links.select(&:id)
但当然,不是那样,因为那行不通,有什么想法吗?:)
解决方案
你可以:
1:
覆盖该eql?(other)
方法,然后数组交集将起作用
class Link < ApplicationRecord
def eql?(other)
self.class == other.class && self.id == other&.id # classes comparing class is a guard here
end
# you should always update the hash if you are overriding the eql?() https://stackoverflow.com/a/54961965/5872935
def hash
self.id.hash
end
end
2:
使用array.select
:
array_links.flat_map {|i| selected_links.select {|k| k.user_id == i.user_id }}
推荐阅读
- spring - 如何手动配置 RestController 的 Request Mapping
- saxon - saxon xpath 3.1,在创建地图时访问变量
- python - 即使每个变量没有被其他线程访问/写入,我是否应该使用锁来写入类变量(在线程期间)?
- php - 使用 preventDefault 后,如何在数据发送到数据库后“重新允许”提交按钮加载页面?
- uml - 逻辑流与控制流
- angularjs - ngRoute Params url 刷新不工作
- java - 如何遍历自定义列表?
- javascript - 使用 Facebook 登录时,我的 react native 应用程序没有更新 redux 商店
- python - 本机 python - 循环数据框并将记录插入数据库
- python - tkinter 小部件在尝试执行时不显示