gpt4 book ai didi

ruby - ruby 中的 `hash` 是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:00 25 4
gpt4 key购买 nike

因为忘记了赋值,所以在写之前读了未定义的局部变量hash。惊喜:没有得到 NameError,值被读取得很好:它是一些 FixNum,程序在很久以后崩溃了。

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

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

这是为什么呢?这是错误还是功能?我在这里读什么?

最佳答案

TL;DR – 这是 hash Ruby 的 top-level 的值对象,等同于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 的文档中:

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

关于ruby - ruby 中的 `hash` 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40504996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com