Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

ruby triple equal

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...