In Ruby Integer === 5
returns true
. Similarly String === "karthik"
returns true
.
However, 5 === Integer
returns false
. And "karthik" === String
.
Why is the operator not commutative?
The simple answer is: because it doesn't make sense. The relationship the operator describes is not commutative, why should the operator be?
Just look at your own examples: 5
is an Integer
. But is Integer
a 5
? What does that even mean?
===
is the case subsumption operator, and subsumption doesn't commute.
The fact that the case subsumption operator uses equals signs, and that it is usually called the triple equals, threequals
or case equality
operator is terribly unfortunate since it not only has absolutely nothing to do with equality, but it also does not conform to many of the laws that equality conforms to, such as transitivity and as you mentioned commutativity.
For more of my ranting about ===
see
===
operator do in Ruby?===
vs. ==
in RubyInteger === 3
work?One very simple reason is that the is_a?
relationship for classes just can't be commutative. Consider the case where both operands are classes:
Class === String
This will return true because String.is_a?(Class)
. However String === Class
will return false, because Class.is_a?(String)
is false and that is of course as it should be.
Another reason is that the semantics of ===
depends on its left operand. This has again two reasons: a) In ruby the semantics always depend on the left operand, because the left operand is the receiver of the method call and b) it is useful, so you can use e.g. classes, ranges and regexen in a case statement with the intended semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With