为什么';t数组覆盖Ruby中的三等号方法?

为什么';t数组覆盖Ruby中的三等号方法?,ruby,language-design,switch-statement,equality,Ruby,Language Design,Switch Statement,Equality,我刚刚注意到数组并没有覆盖三等号方法,它有时被称为大小写相等方法 x = 2 case x when [1, 2, 3] then "match" else "no match" end # => "no match" 而range运算符执行以下操作: x = 2 case x when 1..3 then "match" else "no match" end # => "match" 但是,您可以对阵列执行变通方法: x = 2 case x whe

我刚刚注意到数组并没有覆盖三等号方法,它有时被称为大小写相等方法

x = 2

case x
  when [1, 2, 3] then "match"
  else "no match"
end # => "no match"
而range运算符执行以下操作:

x = 2

case x
  when 1..3 then "match"
  else "no match"
end # => "match"
但是,您可以对阵列执行变通方法:

x = 2

case x
  when *[1, 2, 3] then "match"
  else "no match"
end # => "match"
知道为什么会这样吗

这是因为
x
更可能是一个实际数组而不是一个范围,而数组覆盖
==
意味着普通的等式将不匹配吗

# 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"
因为它是

规范于2009年2月3日由()发布。既然这个答案可能不是你想要的,你为什么不问问他呢

在我看来,你可能在你的问题中使用了一个疯狂的、完全不知情的刺刀。既然功能是通过设计提供的,那么为什么这样做会使测试数组相等性的能力丧失呢?如上所述,在某些情况下,这是有用的


未来的读者应该注意,除非所讨论的数组已经实例化,否则不需要使用数组来匹配多个表达式:

x = 2

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

你的直觉和我的一致。我想不出有多少场景需要将一个范围传递给一个
case
表达式,以使其与其他范围匹配,但我可以想到有几种场景需要传递一个数组,以查看它是否与另一个数组完全匹配。您可能需要向core询问最终答案。我的猜测是数组不是这样的,因为范围是这样的。
x = 2

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