4

これを説明する最良の方法は、例を使用することだと思います。

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 に対して定義する必要があるメソッドはありますか?

4

2 に答える 2

7

とをオーバーライドする必要がありeql?ますhashこれらは、これらの種類のセット操作に使用されるものです。

于 2012-08-30T14:45:46.540 に答える
3

これらのメソッドを A に追加します

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

def hash
  @test.hash
end
于 2012-08-30T14:47:53.750 に答える