ruby - 设置.include?用于 Ruby 中的自定义对象

标签 ruby

我有一个大致这样的类:

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/

相关文章:

ruby - 无方法错误 : undefined method `md5sum'

ruby-on-rails - 从链接预填充表单字段

ruby - 使用.zero?而不是==0?

ruby - Rails 4 和全局化不添加翻译

ruby-on-rails - View 中缺少第一个字段

ruby-on-rails - Rails 3.1/rake - 没有队列的特定于日期的任务

ruby - 在使用 Mechanize 进行抓取时,我总是在 Ruby 2.0 中遇到 UndefinedConversionError

ruby - RSpec Rake 文件,但没有要加载的此类文件 -- rake/tasklib

ruby-on-rails - Railsomniauth 不刷新数据

python - 从 Python 转换后,如何在 Ruby 中通过 HTTP 发布 JSON?