如何使用自定义对象从数组中删除重复项

use*_*702 5 ruby arrays union object

当我调用first_array | second_array两个包含自定义对象的数组时:

first_array = [co1, co2, co3]
second_array =[co2, co3, co4]
Run Code Online (Sandbox Code Playgroud)

它返回[co1, co2, co3, co2, co3, co4]。它不会删除重复项。我试图调用uniq结果,但它也不起作用。我该怎么办?

更新:

这是自定义对象:

class Task
    attr_accessor :status, :description, :priority, :tags
    def initiate_task task_line
        @status = task_line.split("|")[0]
        @description = task_line.split("|")[1]
        @priority = task_line.split("|")[2]
        @tags = task_line.split("|")[3].split(",")
        return self
    end

    def <=>(another_task)
        stat_comp = (@status == another_task.status)
        desc_comp = (@description == another_task.description)
        prio_comp = (@priority == another_task.priority)
        tags_comp = (@tags == another_task.tags)
        if(stat_comp&desc_comp&prio_comp&tags_comp) then return 0 end
    end
end
Run Code Online (Sandbox Code Playgroud)

当我创建几个 Task 类型的实例并将它们放入两个不同的数组时,以及当我尝试调用“|”时 在他们身上什么也没有发生,它只返回包含第一个和第二个数组元素的数组,而没有删除重复项。

fsa*_*via 5

如果您没有实现正确的相等方法,则任何编程语言本身都无法知道两个对象是否不同。对于 ruby​​,您需要实施 eql?和 hash 在你的类定义中,因为这些是 Array 类用来检查相等性的方法,如Ruby 的 Array 文档中所述:

def eql?(other_obj)
  # Your comparing code goes here
end

def hash
  #Generates an unique integer based on instance variables
end
Run Code Online (Sandbox Code Playgroud)

例如:

class A

  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def eql?(other)
    @name.eql?(other.name)
  end

  def hash
    @name.hash
  end
end

a = A.new('Peter')
b = A.new('Peter')

arr = [a,b]
puts arr.uniq
Run Code Online (Sandbox Code Playgroud)

从数组中删除 b 只留下一个对象

希望这可以帮助!