什么是ruby中的`hash`?

因为我忘记了一个赋值,所以在写它之前我会读取未定义的局部变量哈希.惊喜:没有得到一个NameError,而是读取的值很好:它是一些Fixnum,程序崩溃得很晚.

调查问题,我做了以下事情:

>打开irb
>键入hash并按Enter键
>惊喜!答案是-1831075300640432498(令人惊讶的是没有NameError,也没有42)

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

解决方法

TL; DR – 它是 Rubytop-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#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对象(内核)#hash实际上意味着哈希是在内核中定义的,但是如Object的文档中所述:

Although the instance methods of Object are defined by the Kernel module,we have chosen to document them here for clarity.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...