gpt4 book ai didi

ruby - 如何使 Ruby 的数组差(减)方法 `Array#-` 与我的类一起使用?

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

我认为最好的解释方式是举个例子:

class A
attr_accessor :test
def initialize(x = nil)
@test = x
end

def ==(other)
return @test == other.test
end
end

a1 = A.new(1) # => #<A:0x11b7118 @test=1>
a1.test # => 1

a2 = A.new(1) # => #<A:0x11fb0f8 @test=1>
a2.test # => 1

a1 == a2 # => true
[a1].include?(a2) # => true
[a1] - [a2] # => [#<A:0x11b7118 @test=1>]

在这个例子中,我如何让 [a1] - [a2] 返回一个空数组,正如人们对任何其他 Ruby 类所期望的那样?是否有一些我必须为 A 定义的方法我错过了?

最佳答案

您需要覆盖 eql?hash。这些是用于那些类型的集合操作

关于ruby - 如何使 Ruby 的数组差(减)方法 `Array#-` 与我的类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199455/

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