为什么Ruby中Array不重写三等号方法?

问题描述 投票:6回答:1

我刚刚注意到Array没有覆盖三等号方法。===,有时也被称为大小写平等法。

x = 2

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

而范围运算符却可以。

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"
ruby language-design switch-statement equality
1个回答
3
投票

因为它是 在规范中.

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

规格 被加 2009年2月3日,作者 Charles Nutter (@headius). 既然这个答案可能不是你要找的,你为什么不问他呢?

在我看来,在我看来,您可能已经通过使用 啪嗒 的问题。既然设计上有这个功能,为什么要重复,因为这样做会取消测试Array平等的能力?因为 乔丹 上文指出,在某些情况下,这样做是有用的。


未来的读者应该注意,除非相关数组已经被实例化,否则根本没有必要使用数组来匹配多个表达式。

x = 2

case x
  when 1, 2, 3 then "match"
  else "no match"
end # => "match"
© www.soinside.com 2019 - 2024. All rights reserved.