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

独自空忆成欢 提交于 2019-12-08 21:04:13

问题


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"

回答1:


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"


来源:https://stackoverflow.com/questions/7734245/why-doesnt-array-override-the-triple-equal-sign-method-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!