Is ruby ​​a typical eq? and == implementations

I read about the differences between eql? and == in ruby, and I understand that == compares the values, and eql? compares value and type

In accordance with ruby ​​documents:

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

It doesn't seem like the behavior indicated in the documents is automatically inherited, but this is just a suggestion on how to implement these methods. eql? this also mean that if you override either == or eql? then you have to override both?

In the Person class below, is this a typical way to override eql? and == , where the less restrictive == just delegates the more restrictive eql? (it would seem that back would be eql? delegate to == if == implemented only for comparing values, 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
source share
1 answer

Now I get confused, what do aliasing eql docs mean? and == are implemented like this:

 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! 

So why, when you redefine ==, it does not affect eql? even if they are "synonyms". Therefore, in your case, it should be:

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

All Articles