Ruby 典型的 EQL?和 == 实现



我一直在阅读有关 ruby 中 eql?== 之间的差异,我知道==比较值,而eql?比较值和类型

根据 ruby 文档:

对于类 Object 的对象,eql? 与 == 同义。子类通常延续这一传统,但也有例外。

似乎文档中指定的行为并没有自动继承,而这只是有关如何实现这些方法的建议。这是否也意味着,如果您覆盖==eql?,则应覆盖两者?

在下面的类Person中,这是覆盖eql?==的典型方法吗,其中限制较少的==只是委托给限制性更强的eql?(如果实现==只是为了比较值而不是类型,那么将eql?委托给==似乎是倒退的)。

class Person
  def initialize(name) 
    @name = name
  end
  def eql?(other)
    other.instance_of?(self.class) && @name == other.name
  end
  def ==(other)
    self.eql?(other)
  end
protected
    attr_reader :name
end
我现在

感到困惑,文档别名eql是什么意思? 和 == 方法实现如下:

class Test
  def foo
    "foo"
  end
  alias_method :bar, :foo
end
baz = Test.new
baz.foo #=> foo
baz.bar #=> foo
#override method bar
class Test
  def bar
    "bbq!"
  end
end
baz = Test.new
baz.foo #=> foo
baz.bar #=> bbq!

所以这就是为什么当你覆盖==时,它不会影响eql?即使它们是"同义词"。因此,在您的情况下,它应该是:

class Person
  #...
  def ==(other)
    other.instance_of?(self.class) && @name == other.name
  end
  alias_method :eql?, :==
  #...
end

最新更新