The only restriction for a hash key is that it must respond to the
message
hash
with a hash value, and the hash value for a
given key must not change.
This means that certain classes (such as
Array
and
Hash
, as of this writing) can't conveniently be used
as keys, because their hash values can change based on their contents.
If you keep an external reference to an object that is used as a key,
and use that reference to alter the object and change its hash value,
the hash lookup based on that key may not work.
Because strings are the most frequently used keys, and because string
contents are often changed, Ruby treats string keys specially. If you
use a
String
object as a hash key, the hash will duplicate the
string internally and will use that copy as its key. Any changes
subsequently made to the original string will not affect the hash.
If you write your own classes and use instances of them as hash keys, you
need to make sure that either (a) the hashes of the key objects
don't change once the objects have been created or (b) you remember
to call the
Hash#rehash
method to reindex the hash whenever a
key hash
is changed.