开发者

3 Equals or Case Equality operator

开发者 https://www.devze.com 2023-02-01 06:22 出处:网络
In Ruby Integer === 5 returns true. Similarly String === \"karthik\" ret开发者_Python百科urns true.

In Ruby Integer === 5 returns true. Similarly String === "karthik" ret开发者_Python百科urns 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

  • What does the === operator do in Ruby?
  • === vs. == in Ruby
  • How does Integer === 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.


Many operators are not commutative.

The === is called the "case equality operator" because it is called when branching is a case.

It is nice and useful that:

foo = 42
case foo
when Integer
  # branches here
when String
  # etc...
end

It would not be very useful if

foo = Integer
case foo
when 42
# would branch here??
when 666
# etc...
end

Note that in Ruby 1.9, the === operator on a Proc/lambda will call that Proc:

divisible_by_three = ->(x){x % 3 == 0}
divisible_by_three === 42 # => true

Again, very useful in a case statement, but not much in the reverse order.


it needs to implement case-when comparisons

It's normal to have non-commutative operators.

/ - % [] . -> ^ << >> < <= > >= && || = += -= ,

And as it happens, === exists in part as the case-when operator. That's rather elaborate in Ruby, and it couldn't be so if it had to be simplified to a commutative op.

0

精彩评论

暂无评论...
验证码 换一张
取 消