2016-11-09 75 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

雖然對象的實例方法是由內核模塊定義,我們選擇來記錄他們這裏爲了清楚。