开发者

ruby triple equal

开发者 https://www.devze.com 2023-02-24 05:36 出处:网络
Let\'s say that I have following code. result = if a.is_a?(Class) && a <= Exception a.name elsif ...

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

c开发者_运维技巧ase a
when Exception
     a.name
when ...
when ...
end

Do I understand triple equal correctly?


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.


I believe that in your first example you are checking if a is a subclass of Exception (correct me if I'm wrong). The second example just checks if a is an instance of Exception (equivalent to a.is_a?(Exception)).

0

精彩评论

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