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