加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:39:38 所属栏目:百科 来源:网络整理
导读:当我调用first_array时|包含自定义对象的两个数组上的second_array: first_array = [co1,co2,co3]second_array =[co2,co3,co4] 它返回[co1,co4].它不会删除重复项.我试图在结果上调用uniq,但它也没有用.我该怎么办? 更新: 这是自定义对象: class Task at
当我调用first_array时|包含自定义对象的两个数组上的second_array:

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

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

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

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读