I am trying to understand the difference between these four methods. I know by default that == calls the method equal? which returns true when both operands refer to exactly the same object.
=== by default also calls == which calls equal?… okay, so if all these three methods are not overridden, then I guess
===, == and equal? do exactly the same thing?
Now comes eql?. What does this do (by default)? Does it make a call to the operand’s hash/id?
Why does Ruby have so many equality signs? Are they supposed to differ in semantics?
I’m going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they’re overridden in other classes, like String.
Side note: if you want to try these out for yourself on different objects, use something like this:
==— generic "equality"This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.
===— case equalityThis is incredibly useful. Examples of things which have interesting
===implementations:So you can do things like:
See my answer here for a neat example of how
case+Regexcan make code a lot cleaner. And of course, by providing your own===implementation, you can get customcasesemantics.eql?—HashequalitySo you’re free to override this for your own uses, or you can override
==and usealias :eql? :==so the two methods behave the same way.equal?— identity comparisonThis is effectively pointer comparison.