#eql到底如何?”依靠“#hash&quot?
红宝石文档读取如下:
eql?如果OBJ和其他参考相同的哈希键,方法将返回true。
因此,为了使用#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 == hash ==其他。 >已经?
感谢您的提示!
The Ruby docs read as follows:
The eql? method returns true if obj and other refer to the same hash key.
So in order to use #eql?
to compare two objects (or use objects as Hash keys), the object has to implement #hash
in a meaningful manner.
How come the following happens?
class EqlTest
def hash
123
end
end
a = EqlTest.new
b = EqlTest.new
a.hash == b.hash # => true
a.eql? b # => false
I could of course implement EqlTest#eql?
but shouldn't the implementation inherited from Object
be something along the lines of hash == other.hash
already?
Thanks for your hints!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎实际上是相反的。
eql?
有望返回true
返回相同hash
值的对象,但没有定义以比较这些值。您简单地期望您两者都覆盖。This seems to be actually the other way around.
eql?
is expected to returntrue
for objects returning the samehash
value, but it is not defined to compare these values. You are simply expected to override both.