When I go into irb and enter hash, it returns some value such as 2601657421772335946, a Fixnum. What is hash used for?

有帮助吗?

解决方案

Pretty much everything in Ruby responds to hash, including the self in irb. From the fine Object manual:

hash()

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

The Hash class uses the hash value internally to figure out how to arrange Hash keys.

其他提示

When you logged into IRB, self has been set to main ( is an instance of the class Object) . Now when you write hash, it is actually a method Object#hash called on self( which is implicit ).

Arup-iMac:arup$ irb
2.1.0 :001 > self
 => main 
2.1.0 :002 > method(:hash).receiver
 => main 
2.1.0 :003 > self.class
 => Object 
2.1.0 :004 > 

From the doc, why #hash is needed ?

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top