Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `hash` in ruby?

Tags:

ruby

hash

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:

  • Open up irb
  • type hash and press Enter
  • Surprise! the answer is -1831075300640432498 (and surprisingly not NameError, nor 42)

Why is that? Is it a bug or a feature? What am I reading here?

like image 488
Kalsan Avatar asked Nov 09 '16 10:11

Kalsan


1 Answers

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#hash1 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.

like image 87
Stefan Avatar answered Sep 22 '22 01:09

Stefan