Why doesn't Array override the triple equal sign method in Ruby?

I just noticed that Array does not override the triple equal sign === method, which is sometimes called the case equality method.

 x = 2 case x when [1, 2, 3] then "match" else "no match" end # => "no match" 

whereas the range operator:

 x = 2 case x when 1..3 then "match" else "no match" end # => "match" 

However, you can make a workaround for arrays:

 x = 2 case x when *[1, 2, 3] then "match" else "no match" end # => "match" 

Is it known why this is so?

This is because it is more likely that x will be the actual array than the range, and overriding the array === means that regular equality will not match?

 # This is ok, because x being 1..3 is a very unlikely event # But if this behavior occurred with arrays, chaos would ensue? x = 1..3 case x when 1..3 then "match" else "no match" end # => "no match" 
+4
source share
1 answer

Because it is in the specification .

 it "treats a literal array as its own when argument, rather than a list of arguments" 

Specification added February 3, 2009 by Charles Nutter ( @headius ). Since this answer is probably not the one you are looking for, why not ask it?

To take a wild and completely uninformed strike in the dark, it seems to me that you could strike an answer using splat in your question. Since the functionality is available by design, why duplication can remove the possibility of checking the equality of Array? As stated in Jordan , there are situations where this is helpful.


Future readers should keep in mind that if a given array has not already been created, using the array is generally not necessary for matching in several expressions:

 x = 2 case x when 1, 2, 3 then "match" else "no match" end # => "match" 
+2
source

All Articles