Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've just noticed that Array doesn't 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 does:

x = 2

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

You can do a workaround for arrays, however:

x = 2

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

Is it known why this is the case?

Is it because it's more likely for x to be an actual array than a range, and array overriding === would mean that ordinary equality would not be a 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"
like image 612
Andrew Grimm Avatar asked Oct 12 '11 01:10

Andrew Grimm


1 Answers

Because it's in the specification.

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

The spec was added February 3, 2009 by Charles Nutter (@headius). Since this answer's probably not what you're looking for, why don't you ask him?

To take a wild and completely uninformed stab in the dark, it seems to me that you might have hit upon the answer by using a splat in your question. Since the functionality is available by design, why duplicate when doing so would remove the ability to test Array equality? As Jordan points out above, situations exist where this is useful.


Future readers should note that unless the array in question is already instantiated, using an array at all is not necessary to match on multiple expressions:

x = 2

case x
  when 1, 2, 3 then "match"
  else "no match"
end # => "match"
like image 143
Alec Wenzowski Avatar answered Nov 16 '22 23:11

Alec Wenzowski