Set.include? for custom objects in Ruby

I have a class something like this:

class C
    attr_accessor :board # board is a multidimensional array (represents a matrix)

    def initialize
        @board = ... # initialize board
    end   

    def ==(other)
        @board == other.board
    end
end

However, when I do this:

s = Set.new
s.add(C.new)
s.include?(C.new) # => false

Why?

+4
source share
3 answers

Setuses eql?and hash, and not ==, to check two objects for equality. See, for example, this documentation for Set : "Is the equality of each pair of elements defined according to Object # eql? And Object # hash, since Set uses the Hash as storage."

If you want two different objects to Cbe the same for your established membership, you will have to override these two methods.

class C
  attr_accessor :board 

  def initialize
    @board = 12
  end

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

   def hash
    @board.hash
  end
end

s = Set.new
s.add C.new
s.include? C.new   # => true
+2
source

You need to do something below:

require 'set'
class C
  attr_accessor :board 

  def initialize
    @board = 12
  end

  def ==(other)
    @board == other.board
  end
end
s = Set.new
c = C.new
s.add(c)
s.include? c # => true

:

s.add(C.new)
s.include?(C.new) # => false

C.new, 2 . C.new , 3 :

C.new.object_id # => 74070710
C.new.object_id # => 74070360
C.new.object_id # => 74070030

. C, s, Set#add, C, Set#include?, - . , , , .

+1
class C
    attr_accessor :board # board is a multidimensional array (represents a matrix)

    def initialize
        board = [[1],[2]] # initialize board
        p @board #=> nil !!

    end 
    def ==(other)
        @board == other.board
    end

    def eql?(other) # not used
        puts "eql? called"
        @board == other.board
    end
    def ==(other) # not used
        puts "== called"
        @board == other.board
    end

    def hash
      puts "hash called"
      board.hash
    end
end
require 'set'
s = Set.new
s.add(c = C.new)
p s.include?(c) 

Installs the Hash as storage under it. Exit:

nil
hash called
hash called
true
+1
source

All Articles