我在 irb 或 Rails 控制台中输入了 hash
,我可以看到它包含一些随机值。我不知道它是应该存在还是由某个 gem 完成。
这里:
hash # => -943824087729528496
再试一次:
hash # => 3150408717325671348
这正常吗?如果有,有什么用?或者该值是什么意思?
最佳答案
在 Ruby 中,所有顶级方法调用都发生在 main
对象上:
self
#=> main
main
是一个类为 Object
的对象:
self.class
#=> Object
所以在顶层,hash
调用 Object#hash
main
对象上的方法:
hash → fixnum
Generates a Fixnum hash value for this object. This function must have the property that
a.eql?(b)
impliesa.hash == b.hash
.The hash value is used along with eql? by the Hash class to determine if two objects reference the same hash key. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.
The hash value for an object may not be identical across invocations or implementations of Ruby. If you need a stable identifier across Ruby invocations and implementations you will need to generate one with a custom method.
有关 Ruby 顶层的更多信息,请参阅博客文章 What is the Ruby Top-Level? .
关于ruby - 是否有默认变量 `hash` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164433/