“#eql”究竟如何?依靠“#hash”?
How exactly does "#eql?" rely on "#hash"?
Ruby 文档内容如下:
The eql? method returns true if obj and other refer to the same hash key.
所以为了使用#eql?
比较两个对象(或使用对象作为哈希键),对象必须以有意义的方式实现#hash
。
怎么会出现下面的情况?
class EqlTest
def hash
123
end
end
a = EqlTest.new
b = EqlTest.new
a.hash == b.hash # => true
a.eql? b # => false
我当然可以实现 EqlTest#eql?
,但是从 Object
继承的实现不应该已经与 hash == other.hash
类似吗?
感谢您的提示!
这似乎恰恰相反。 eql?
预期 return true
对于对象 return 具有相同的 hash
值,但未定义比较这些值。您只是希望覆盖两者。
The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For any pair of objects where eql? returns true, the hash value of both objects must be equal. So any subclass that overrides eql? should also override hash appropriately.
Ruby 文档内容如下:
The eql? method returns true if obj and other refer to the same hash key.
所以为了使用#eql?
比较两个对象(或使用对象作为哈希键),对象必须以有意义的方式实现#hash
。
怎么会出现下面的情况?
class EqlTest
def hash
123
end
end
a = EqlTest.new
b = EqlTest.new
a.hash == b.hash # => true
a.eql? b # => false
我当然可以实现 EqlTest#eql?
,但是从 Object
继承的实现不应该已经与 hash == other.hash
类似吗?
感谢您的提示!
这似乎恰恰相反。 eql?
预期 return true
对于对象 return 具有相同的 hash
值,但未定义比较这些值。您只是希望覆盖两者。
The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For any pair of objects where eql? returns true, the hash value of both objects must be equal. So any subclass that overrides eql? should also override hash appropriately.