Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 Equals or Case Equality operator

Tags:

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?

like image 344
karthiks Avatar asked Dec 24 '10 16:12

karthiks


2 Answers

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

  • What does the === operator do in Ruby?
  • === vs. == in Ruby
  • How does Integer === 3 work?
like image 101
Jörg W Mittag Avatar answered Sep 28 '22 10:09

Jörg W Mittag


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.

like image 24
sepp2k Avatar answered Sep 28 '22 11:09

sepp2k