Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Ruby's Array difference (minus) method, `Array#-`, work with my classes?

Tags:

ruby

I think the best way to explain this is with an example:

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>]

In this example, how would I get [a1] - [a2] to return an empty array, as one would expect it to for any other Ruby class? Is there some method that I have to define for A that I'm missing?

like image 784
Ajedi32 Avatar asked Dec 26 '22 18:12

Ajedi32


2 Answers

You need to override eql? and hash. These are the ones that are used for those kinds of set operations.

like image 193
Jörg W Mittag Avatar answered Dec 29 '22 11:12

Jörg W Mittag


Add these methods to A

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

def hash
  @test.hash
end
like image 40
Tim Destan Avatar answered Dec 29 '22 11:12

Tim Destan