Ruby中的`hash`是什么?

6
因为我忘了一个作业,写之前读取了未定义的本地变量 hash。惊奇的是:与其出现 NameError 错误,它确实被读取了,而且是 FixNum 类型的一些值,程序在之后崩溃了。
研究这个问题,我做了以下几步:
  • 打开 irb
  • 输入 hash 并按 Enter 键
  • 惊奇!答案是 -1831075300640432498(并不是 NameError 或 42)
为什么会这样?这是一个 bug 还是特性?我在这里读到了什么?

3
http://ruby-doc.org/core-2.0.0/Object.html#method-i-hash - Aleksei Matiushkin
1个回答

8

TL;DR – 它是Ruby的顶层对象的hash值,相当于self.hash

这里有一点调试帮助:

irb(main):001:0> hash
#=> 3220857809431415791

irb(main):002:0> defined? hash
#=> "method"

irb(main):003:0> method(:hash)
#=> #<Method: Object(Kernel)#hash>

现在您可以在线查找 Object#hash1

http://ruby-doc.org/core-2.3.1/Object.html#method-i-hash

或者在IRB中:

irb(main):004:0> help "Object#hash"
= Object#hash

(from ruby core)
------------------------------------------------------------------------------
  obj.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.


#=> nil
irb(main):005:0>

1 Object(Kernel)#hash 实际上意味着 hash 是在 Kernel 中定义的,但是根据 Object 的文档所述:

尽管 Object 的实例方法是由 Kernel 模块定义的,但出于清晰起见,我们选择在此处记录它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接