如何使用Ruby的数组差异(减号)方法,`Array#-`,使用我的类?

时间:2012-08-30 14:40:20

标签: ruby

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

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定义的方法我不知道?

2 个答案:

答案 0 :(得分:7)

您需要覆盖eql?hash。这些是用于那些设置操作的那些。

答案 1 :(得分:3)

将这些方法添加到A

def eql?(other)
  @test == other.test
end

def hash
  @test.hash
end