2016-11-09 45 views
6

因为我忘了一个任务,我写之前阅读未定义的局部变量hash。惊喜:不是得到一个NameError,而是读取的值很好:它是一些FixNum,程序在晚些时候崩溃。ruby​​中的`hash`是什么?

调查的问题,我做了以下内容:

  • 打开IRB
  • hash,然后按Enter
  • 惊喜!答案是-1831075300640432498(并且出人意料地不是NameError,也不是42)

这是为什么?它是一个错误还是一个功能?我在这里读什么?

+3

http://ruby-doc.org/core-2.0.0/Object.html#method-i-hash – mudasobwa

回答

8

TL; DR - 它是用于Ruby的top-level对象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#hash 在线:

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> 

Object(Kernel)#hash实际上意味着hashKernel定义,但如文档中所述的用于Object

虽然对象的实例方法是由内核模块定义,我们选择来记录他们这里为了清楚。