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
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.
Related
Is all equality in Ruby is "strict", analogous to === in PHP? I notice that there is a === operator in Ruby but it does something different.
=== is not an equality operator!
Not.
But, what is it?
You might be familiar with === as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics from other languages.
So what does === do?
=== is the pattern matching operator!
=== matches regular expressions
=== checks range membership
=== checks being instance of a class
=== calls lambda expressions
=== sometimes checks equality, but mostly it does not
So how does this madness make sense?
Enumerable#grep uses === internally
case when statements use === internally
That is why you can use regular expressions and classes and ranges and even lambda expressions in a case when statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c
# value matches one of a, b, c with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value too, as well as with grep method.
I can only guess why there's no !== method but Tadman's intuition seems spot on, === is mostly used indirectly through case when and grep and thus likely didn't seem to need an explicit inverse operator. Most style guides for production code ban the use of === operator anyway.
If you are looking for other equality operators, check .eql? and .equal?
Ruby doesn't need a strict ===-type operator because the default comparator == is already quite strict, unlike PHP and others. It's not often the case any sort of conversion is done, so the cases where it is performed stand out as exceptional:
0 == ""
# => false
0 == "0"
# => false
"" == " "
# => false
0 == nil
# => false
0 == 0.0
# => true
In fact when you do use === you're often asking for trouble by being overly specific or inviting unexpected behaviour:
"" === String
# => false
String === ""
# => true
String === Object
# => false
Object === String
# => false
The meaning of === is defined by various classes in different ways to mean things often unrelated to "equality". It's just a shorthand like << is at times. Object === String is actually Object.===(String) which is why it produces different results from String.===(Object). In that case it means "is equal to or a derived class of...".
It's because of this relative rarity that !== doesn't really need to exist in the first place. === is often used only indirectly, as it's the default method for comparing things via a case statement.
Ah... after digging deeper I think I answered my own question. Ruby has .eql? .equal? link
Ruby's equality is not strict using ==, at least not like === in JavaScript. Ruby has stricter equality methods, such as eql? and equal?, but the === is not for strict equality. The === method is called the subsumption operator. It's most used implicitly in case statements. This is to say that
case a
when b ...
when c ...
else ...
end
is equivalent to
if b === a
...
elsif c === a
...
else
...
end
Having said that, !== could exist, but instead it is just left for the user to do !(a === b). Note that === is not commutative as in a === b is not the same as b === a.
https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#Logical_Or
The binary "or" operator will return the logical disjunction of its
two operands. It is the same as "||" but with a lower precedence
As I understand it, as || has a higher precedence than "or", the code below will first test if 'b' is true, then 'c', and then if both are false will test 'a'. I would like to witness this but am not sure if my understanding is incorrect, or simply my test.
a = true
b = false
c = false
p a or b || c
==> true #but were b and c checked as expected?
My attempt to test this is as follows..
def atest
a = "string a"
a.include? 'string'
a
end
def btest
b = "string b"
b.include? 'string'
b
end
def ctest
c = "string c"
c.include? 'string'
c
end
puts "#{atest or btest || ctest}"
==> string a
I expected 'string b' to be returned... I'm completely new to programming since a week ago so I'm not sure, is my code wrong or is my understanding of the quote wrong?
edit: Appreciation on its own seems to be discouraged in responses, so I'll hide it here. Cheers for all the answers/further reading/code cleanup, it's clear now where I was going wrong.
In Ruby, &&, and, ||, and or are short-circuit operators:
[...] the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
In your example:
a or b || c
Ruby evaluates a, sees a truthy value and immediately returns it, without evaluating b || c.
or's lower precedence means that the expression is evaluated as:
a or (b || c)
instead of:
(a or b) || c
Just like
1 + 2 * 3
is evaluated as:
1 + (2 * 3)
because + has lower precedence than *.
But it doesn't change the order of evaluation. 1 is still evaluated before 2 * 3.
Also note that due to or's very low precedence
p a or b || c
is evaluated as:
(p a) or (b || c)
Neither b nor c will ever be printed this way.
Further readings:
Using “and” and “or” in Ruby
How to use Ruby’s English and/or operators without going nuts
Ruby: On The Perl Origins Of “&&” And “||” Versus “and” And “or”.
Sidenote: In your code there are lines that basically do nothing: a.include? 'string' is silently returning truthy, having no impact at all on the running code. These three functions might be rewritten as:
def atest
"string #{__callee__[0]}"
end
alias :btest :atest
alias :ctest :atest
You are confusing operator precedence with normal execution flow. Operator precedence is about what operation to execute in advance when we have two operations applied to the same operand. Otherwise, the execution order is left-to-right. E.g.
a + b * c
is executed as:
a
b
# oh! ambiguity: lookup the precedence table: will do multiplication
c # (otherwise a + b)
*
+
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
=== vs. == in Ruby
I've seen it used a few times lately but can't figure out what it does. Can anyone illustrate how it works?
Just like with every other method in Ruby (or actually pretty much any object-oriented language),
a === b
means whatever the author of a's class wants it to mean.
However, if you don't want to confuse the heck out of your colleagues, the convention is that === is the case subsumption operator. Basically, it's a boolean operator which asks the question "If I have a drawer labelled a would it make sense to put b in that drawer?"
An alternative formulation is "If a described a set, would b be a member of that set?"
For example:
(1..5) === 3 # => true
(1..5) === 6 # => false
Integer === 42 # => true
Integer === 'fourtytwo' # => false
/ell/ === 'Hello' # => true
/ell/ === 'Foobar' # => false
The main usage for the === operator is in case expressions, since
case foo
when bar
baz
when quux
flurb
else
blarf
end
gets translated to something (roughly) like
_temp = foo
if bar === _temp
baz
elsif quux === _temp
flurb
else
blarf
end
Note that if you want to search for this operator, it is usually called the triple equals operator or threequals operator or case equality operator. I really dislike those names, because this operator has absolutely nothing whatsoever to do with equality.
In particular, one would expect equality to be symmetric: if a is equal to b, then b better be also equal to a. Also, one would expect equality to be transitive: if a == b and b == c, then a == c. While there is no way to actually guarantee that in a single-dispatch language like Ruby, you should at least make an effort to preserve this property (for example, by following the coerce protocol).
However, for === there is no expectation of either symmetry or transitivity. In fact, it is very much by design not symmetric. That's why I don't like calling it anything that even remotely resembles equality. It's also why I think, it should have been called something else like ~~~ or whatever.
Thanks for your edit Jacob, I was about to call you out ;) I'll post a couple of examples anyway. The implementation of === differs depending on type. For example:
(1...3) === 2
=> true
/test/ === "this is a test"
=> true
case 'test'
when /blah/
"Blach"
when /test/
"Test"
else
"Fail"
end
=> "Test"
Stephen, checkout http://ruby-doc.org/docs/ProgrammingRuby/ (the "Pickaxe"), it should be able to help you out with questions such as this in the future.
In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.
To my knowledge, Ruby doesn't have true operators, they are all methods which are invoked on the LHS of the expression, passing in the RHS of the expression.
So, really, you could override any "operator" you want in your classes to perform whatever the heck you want (analogous to operator overloading in C++).
This article mentions 4 ways to invoke procs in ruby 1.9, and === is one of them. I don't understand why this would be done this way at all. Does it have any relationship to the normal meaning of === (asking if the two objects are the same object)?
irb(main):010:0> f =-> n {[:hello, n]}
=> #
irb(main):011:0> f.call(:hello)
=> [:hello, :hello]
irb(main):012:0> f === :hello
=> [:hello, :hello]
irb(main):013:0> Object.new === Object.new
=> false
irb(main):014:0> f === f
=> [:hello, #]
Note that === in Ruby is NOT about equality, unlike JavaScript. It is specifically used for case expressions:
case cats.length
when 42 # Uses 42 === cats.length
puts :uh
when /cool/i # Uses /cool/i === cats.length
puts :oh
when ->(n){ n.odd? || n/3==6 } # Passes cats.length to the proc
puts :my
end
This is what the docs have to say:
It is to allow a proc object to be a target of when clause in the
case statement.
This is a, perhaps contrived, example:
even = proc { |x| x % 2 == 0 }
n = 3
case n
when even
puts "even!"
else
puts "odd!"
end
It works because the case/when is basically executed like this:
if even === n
puts "even!"
else
puts "odd!"
end
The case/when checks which branch to execute by calling === on the arguments to when clauses, picking the first that returns a truthy value.
Despite its similarity to the equality operator (==) it not a stronger or weaker form of it. I try to think of the === operator as the "belongs to" operator. Class defines it so that you can check if an object belongs to the class (i.e. is an instance of the class or a subclass of the class), Range defines it as to check if the argument belongs to the range (i.e. is included in the range), and so on. This doesn't really make the Proc case make more sense, but think of it as a tool for making your own belongs to operators, like my example above; I defined an object that can determine if something belongs to the set of even numbers.
This feature is useful in case construction, when you need to calculate something at the comparing.
is_odd =-> n { n%2 != 0 }
is_even =-> n { n%2 == 0 }
case 5
when is_even
puts "the number is even"
when is_odd
puts "the number is odd"
end
=> the number is odd
Does it have any relationship to the normal meaning of === (asking if the two objects are the same object)?
Actually, that's a common misconception about === in Ruby. It's actually not strictly for Object#object_id comparison (although that is its behavior in many common invocations). In Ruby, === is case subsumption.
Here's the description of === from Object: "Case Equality -- For class Object, effectively the same
as calling #==, but typically overridden by descendants
to provide meaningful semantics in case statements."
Sadly, even though it is comprised of three =, it doesn't have anything even remotely to do with equality :-D
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
=== vs. == in Ruby
I've seen it used a few times lately but can't figure out what it does. Can anyone illustrate how it works?
Just like with every other method in Ruby (or actually pretty much any object-oriented language),
a === b
means whatever the author of a's class wants it to mean.
However, if you don't want to confuse the heck out of your colleagues, the convention is that === is the case subsumption operator. Basically, it's a boolean operator which asks the question "If I have a drawer labelled a would it make sense to put b in that drawer?"
An alternative formulation is "If a described a set, would b be a member of that set?"
For example:
(1..5) === 3 # => true
(1..5) === 6 # => false
Integer === 42 # => true
Integer === 'fourtytwo' # => false
/ell/ === 'Hello' # => true
/ell/ === 'Foobar' # => false
The main usage for the === operator is in case expressions, since
case foo
when bar
baz
when quux
flurb
else
blarf
end
gets translated to something (roughly) like
_temp = foo
if bar === _temp
baz
elsif quux === _temp
flurb
else
blarf
end
Note that if you want to search for this operator, it is usually called the triple equals operator or threequals operator or case equality operator. I really dislike those names, because this operator has absolutely nothing whatsoever to do with equality.
In particular, one would expect equality to be symmetric: if a is equal to b, then b better be also equal to a. Also, one would expect equality to be transitive: if a == b and b == c, then a == c. While there is no way to actually guarantee that in a single-dispatch language like Ruby, you should at least make an effort to preserve this property (for example, by following the coerce protocol).
However, for === there is no expectation of either symmetry or transitivity. In fact, it is very much by design not symmetric. That's why I don't like calling it anything that even remotely resembles equality. It's also why I think, it should have been called something else like ~~~ or whatever.
Thanks for your edit Jacob, I was about to call you out ;) I'll post a couple of examples anyway. The implementation of === differs depending on type. For example:
(1...3) === 2
=> true
/test/ === "this is a test"
=> true
case 'test'
when /blah/
"Blach"
when /test/
"Test"
else
"Fail"
end
=> "Test"
Stephen, checkout http://ruby-doc.org/docs/ProgrammingRuby/ (the "Pickaxe"), it should be able to help you out with questions such as this in the future.
In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.
To my knowledge, Ruby doesn't have true operators, they are all methods which are invoked on the LHS of the expression, passing in the RHS of the expression.
So, really, you could override any "operator" you want in your classes to perform whatever the heck you want (analogous to operator overloading in C++).