Let's say that I have following code.
result = if a.is_a?(Class) && a <= Exception
a.name
elsif ...
elsif ...
end
I refactored this code to
case a
when Exception
a.name
when ...
when ...
end
Do I understand triple equal correctly?
Triple Equals Operator (More Than Equality) Ruby is calling the === method here on the class. This compares the current class with the other object's class.
When using triple equals === in JavaScript, we are testing for strict equality. This means both the type and the value we are comparing have to be the same.
Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
Two strings or boolean values, are equal if they both have the same length and value. In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.
We can't tell whether you truly get === or not from such a limited example. But here's a break down of what's really happening when you use ===, either explicitly or implicitly as part of a case/when statement such as the one used in the example..
The triple equal(===) has many different implementations that depend on the class of the left part. It's really just an infix notation for the .=== method. Meaning that the following statements are identical:
a.=== b
a === b
The difference doesn't look like much, but what it means is that the left hand side's === method is being invoked instead of some magical operator defined on the language level, that's like == but not quite. Instead === is defined in each class that uses it, maybe in an inherited class or Mixin.
The general definition of the triple equals is that it will return true if both parts are identical or if the right part is contained within the range of the left.
In the case of Class.===, the operation will return true if the argument is an instance of the class (or subclass). In the case where the left side is a regular expression, it returns true when the right side matches the regular expression.
The when of case is an implied === which compares the case variable to the when clause using === so that the following two statements produce the same result.
case a
when String
puts "This is a String"
when (1..3)
puts "A number between 1 and 3"
else
puts "Unknown"
end
if String === a
puts "This is a String"
elsif (1..3) === a
puts "A number between 1 and 3"
else
puts "Unknown"
end
Check the documentation for the types you use on the left hand of a === or in a when statement to be sure exactly how things work out.
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