为什么Array不覆盖Ruby中的三等号方法? [英] Why doesn't Array override the triple equal sign method in Ruby?

查看:47
本文介绍了为什么Array不覆盖Ruby中的三等号方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到Array并没有覆盖三重等号方法===,有时也称为大小写相等方法.

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?

是不是因为x可能是实际数组而不是范围,并且数组覆盖===意味着普通等式不会匹配?

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"

推荐答案

因为它是

Because it's in the specification.

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

添加了 2009年2月3日查尔斯·纳特( @ headius ).由于此答案可能不是您要查找的,所以为什么不问他?

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?

要在黑暗中采取狂野而完全不知情的刺,在我看来,您可能已经通过使用 Jordan 所指出的那样,存在一些有用的情况.

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"

这篇关于为什么Array不覆盖Ruby中的三等号方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆