Because I forgot an assignment, I read the undefined local variable hash
before writing it. Surprise: Instead of getting a NameError, the value was read just fine: It was some FixNum and the program crashed much later.
Investigating on the problem, I did the following:
hash
and press EnterWhy is that? Is it a bug or a feature? What am I reading here?
TL;DR – it's the hash
value for Ruby's top-level object, equivalent to self.hash
.
Here's a little debugging help:
irb(main):001:0> hash
#=> 3220857809431415791
irb(main):002:0> defined? hash
#=> "method"
irb(main):003:0> method(:hash)
#=> #<Method: Object(Kernel)#hash>
You can now lookup Object#hash
1 online:
http://ruby-doc.org/core-2.3.1/Object.html#method-i-hash
Or in 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>
1Object(Kernel)#hash
actually means that hash
is defined in Kernel
, but as stated in the documentation for Object
:
Although the instance methods of Object are defined by the Kernel module, we have chosen to document them here for clarity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With