3 Equals or Case Equality operator

狂风中的少年 提交于 2019-12-17 19:31:46

问题


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?


回答1:


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?



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4527220/3-equals-or-case-equality-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!