在本次演讲中,演讲者创建了一个价值类。
在实现它时,他重写#eql?并说在 Java 开发中,习惯用法是无论何时重写#eql?都必须重写#hash.
class Weight
# ...
def hash
pounds.hash
end
def eql?(other)
self.class == other.class &&
self.pounds == other.pounds
end
alias :== eql?
end
Run Code Online (Sandbox Code Playgroud)
首先,#hash方法是什么?我可以看到它返回一个整数。
> 1.hash
=> -3708808305943022538
> 2.hash
=> 1196896681607723080
> 1.hash
=> -3708808305943022538
Run Code Online (Sandbox Code Playgroud)
使用 pry 我可以看到一个整数响应,#hash但我看不到它从哪里继承该方法。它没有在Numeric或 上定义Object。如果我知道这个方法做了什么,我可能会理解为什么它需要与#eql?.
那么,为什么#hash每次被覆盖时都需要eql?被覆盖?
ruby ×1