3

I typed hash in irb or in Rails console, and I can see it holds some random value. I do not know if it should be there or it's done by some gem.

Here:

hash # => -943824087729528496

Trying again:

hash # => 3150408717325671348 

Is this normal? If so, what's the use? Or what does that value mean?

sawa
  • 165,429
  • 45
  • 277
  • 381
shivam
  • 16,048
  • 3
  • 56
  • 71
  • 3
    `defined?(hash)` reveals that it's a method and `method(:hash)` shows its origin – Stefan Jul 01 '15 at 14:55
  • @Stefan I should have done that, but I guess I got too overwhelmed by my discovery to ask a question here :P – shivam Jul 01 '15 at 15:09

3 Answers3

6

In Ruby, all top level method calls happen on the main object:

self
#=> main 

main is an object with the class Object:

self.class
#=> Object

So at the top level, hash calls the Object#hash method on the main object:

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.

For more on the top-level in Ruby, see the blog post What is the Ruby Top-Level?.

Ajedi32
  • 45,670
  • 22
  • 127
  • 172
1

By calling hash from the pry/irb one just calls Object#hash on main.

Community
  • 1
  • 1
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

hash is a method on object(docs)

Its part of the "top level" more info

DickieBoy
  • 4,886
  • 1
  • 28
  • 47