首页 > 解决方案 > 根据属性对两个数组进行交集后返回对象

问题描述

我有两个数组,都填充了具有许多属性的对象。两个数组都持有相同的对象类型。我想根据对象的属性查找对象匹配的位置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)

但当然,不是那样,因为那行不通,有什么想法吗?:)

标签: arraysrubyintersection

解决方案


你可以:

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 }}

推荐阅读