ruby - 为什么 Array 不覆盖 Ruby 中的三重等号方法?

标签 ruby language-design switch-statement equality

我刚刚注意到 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"

最佳答案

因为它是 in the specification .

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

规范 was added 2009 年 2 月 3 日 Charles Nutter (@headius)。既然这个答案可能不是您要找的,为什么不问问他呢?

要在黑暗中进行一次疯狂且完全不知情的刺杀,在我看来,您可能已经通过使用 a splat 找到了答案。在你的问题中。由于该功能是按设计提供的,为什么在这样做时重复会删除测试数组相等性的能力?作为Jordan上面指出,在某些情况下这是有用的。


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

x = 2

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

关于ruby - 为什么 Array 不覆盖 Ruby 中的三重等号方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734245/

相关文章:

ruby-on-rails - Rails 如何使用 where 对多列进行排序?

ruby-on-rails - 使用 ruby​​ on Rails 进行定时服务器事件

java - 如何使用 mockito 测试主要功能的开关案例?

java - Scala 的单例在序列化方面有哪些保证?

ios - 如何根据变化的属性在 Swift 中实现 enum 和 switch 语句?

java - 具有多个用例的onOff开关的SharedPreferences

ruby-on-rails - 在 Amazon S3 carrierwave 上重新上传图片

ruby - 使用大括号是否违反 "Ruby way"?

ruby - 一种语言如何被自身解释(如 Rubinius)?

c# - F# 缺少面向对象或命令式的什么?