ruby object.hash

ruby

Solution

For objects to be stored in hashmaps or hashsets the following must hold true:

If two objects are considered equal, their hash value must also be equal.

If two objects are not considered equal, their hash value should be likely to be different (the more often two different objects have the same hash value, the worse the performance of operations on the hashmap/set).

So if two objects have the same hash value there is a good chance (but no guarantee) that they are equal.

What exactly "equal" means in the above is up to the implementor of the hash method. However you should always implement `eql?` to use the same definition of equality as hash.

For classes that don't override hash (i.e. classes using Object's hash implementation) hash equality is defined in terms of object identity. I.e. two objects are considered equal if and only if the reside at the same location in memory.

In ruby up to 1.8.6 Array and Hash did not override `hash`. So if you used arrays (or hashes) as hash keys, you could only retrieve the value for a key, if you used the exact same array as a key for retrieval (not an array with the same contents).

In ruby 1.8.7+ `Array#hash` and `Hash#hash` (as well as their `eql?` methods) are defined so that they are equal when their elements are equal.

Problem

What's the meaning of an object's hash value? And in which case does two object has the same hash value?? Also it is said that Array|Hash can't be Hash keys, this has something to do with object's hash value, why?

Original source