Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default variable `hash`?

Tags:

ruby

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?

like image 252
shivam Avatar asked Dec 05 '25 14:12

shivam


1 Answers

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?.

like image 168
Ajedi32 Avatar answered Dec 07 '25 10:12

Ajedi32



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!