gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:19 27 4
gpt4 key购买 nike

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

first_array = [co1, co2, co3]
second_array =[co2, co3, co4]

它返回 [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

当我创建几个 Task 类型的实例并将它们放入两个不同的数组时,当我尝试调用“|”时在它们上没有任何反应,它只是返回包含第一个和第二个数组元素的数组,没有删除重复项。

最佳答案

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

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

def hash
#Generates an unique integer based on instance variables
end

例如:

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

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

希望这对您有所帮助!

关于ruby - 如何使用自定义对象从数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com