What is a hash in a ruby?

Since I forgot the purpose, I read the local variable undefined hash before writing it. Surprise: instead of getting the NameError value, the value was read just fine: it was FixNum, and the program was broken much later.

Exploring the problem, I did the following:

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

Why? Is this a bug or a function? What am I reading here?

+6
source share
1 answer

TL DR is the hash value for Ruby top-level , which is equivalent to self.hash .

Here is some 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> 

Now you can search for 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> 

1 Object(Kernel)#hash means that hash is defined in Kernel , but as stated in the documentation for Object :

Although the object instance methods are defined by the kernel module, we decided to write them here for clarity.

+8
source

Source: https://habr.com/ru/post/1012173/


All Articles