我刚刚注意到数组不会覆盖三重等号方法===
,有时称为大小写相等法。
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"
因为它是在规范中.
it "treats a literal array as its own when argument, rather than a list of arguments"
规格加入2009 年 2 月 3 日查尔斯·纳特 (@headius)。既然这个答案可能不是你想要的,你为什么不问他呢?
在黑暗中进行一次疯狂且完全不知情的尝试,在我看来,您可能已经通过使用找到了答案a splat在你的问题中。既然该功能是按设计可用的,为什么重复这样做会消除测试数组相等性的能力呢?作为Jordan上面指出,存在这种有用的情况。
未来的读者应该注意,除非所讨论的数组已经实例化,否则根本不需要使用数组来匹配多个表达式:
x = 2
case x
when 1, 2, 3 then "match"
else "no match"
end # => "match"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)