6

I've been reading about the differences between eql? and == in ruby, and I understand that == compares the values while eql? compares the value and the type

According to the ruby docs:

For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions.

It does not seem like the behavior specified in the docs is automatically inherited, but rather this is just a suggestion of how to implement these methods. Does this also imply that if you override either == or eql? then you should override both?

In the class Person below, is this the typical way of overridding eql? and ==, where the less restrictive == just delegates to the more restrictive eql? (it would seem backwards to have eql? delegate to == if == was only implemented to compare values and not types).

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
4

1 回答 1

4

我现在很困惑,文档中的 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
于 2012-06-28T05:32:43.930 回答