I just spent several hours of investigating a problem that I had when
using instances of my own class as keys in a Hash. If you, like me, have
experience with this from a language like Java, you know that you have
to override both the hash method and the equality operator/method. What
took me by surprise was that Hash does NOT use the == operator when
comparing keys. Instead, it uses the eql? method. Thus, it is the eql?
method you have to define for your classes.
The above is actually documented in the Ruby core docs - but not in the
most obvious place in my opinion. It is mentioned only in the
Object.hash documentation. I never considered looking there for the
answer - I only looked at the docs for Hash and it makes no mention of
this fact. This may be my fault. But in my opinion this behavior is a
feature of the Hash class first and foremost. As such it is rather
important to document it in the Hash class.
P.S. One reason it took me so long to figure out is that Googling for
words like “hash”, “key”, etc. is not very specific and gives way too
many unrelated results.