我有一个大致这样的类:
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
仍然,当我这样做时:
s = Set.new
s.add(C.new)
s.include?(C.new) # => false
为什么?
最佳答案
Set
使用 eql?
和 hash
,而不是 ==
,来测试两个对象是否相等。参见,例如,this documentation of Set : "每对元素的相等性根据 Object#eql? 和 Object#hash 确定,因为 Set 使用 Hash 作为存储。"
如果您希望两个不同的 C
对象的集合成员相同,则必须覆盖这两个方法。
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
关于ruby - 设置.include?用于 Ruby 中的自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19411184/