ruby - 是否有默认变量 `hash` ?

标签 ruby

我在 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) implies a.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/

相关文章:

ruby-on-rails - Rails 5 - config.assets.compile 应该是真的 - 为什么?

ruby - 打开文件后检查文件是否在关闭时被修改

ruby - ruby 类的局部变量

ruby-on-rails - 事件记录查询忽略零值

ruby - 如何将 Parslet 与字符串而不是 Parslet 切片一起使用

ruby-on-rails - Rails CSV 导入文件的标题不在模型中

ruby - 如果不是插件,请明确指定 Vagrantfile 路径

ruby-on-rails - 无法在 Rails 中预先检查 check_box_tag

ruby-on-rails - 大于一的方法?

Ruby Mechanize 表单输入字段文本