【发布时间】:2021-03-08 05:00:18
【问题描述】:
在使用新的case ... in pattern matching in Ruby 时,是否有防止nil 绑定到变量的好方法?
case method()
in ... # Some cases here
...
in ...
...
in variable # If previous clauses did not match, then capture to variable
puts variable
else # How to prevent that variable also captures nil?
puts "Nil" # -> This is not called if method() returns nil
end
我找到了以下两种方法,但它们看起来很丑:
1.) 使用if 限定符
case method()
in ... # Some cases here
...
in ...
...
in variable if variable
puts variable
else
puts "Nil"
end
2.) 反向匹配顺序
case method()
in ... # Some cases here
...
in ...
...
in nil
puts "Nil"
in variable # Catch all
puts variable
end
还有更好的吗?
这还能怎么用?这将允许一种使用单行模式匹配表达式对nil 进行比较和赋值的好方法:
if method() => variable
...
end
(这个问题的灵感来自a question on assignments in if statements)
【问题讨论】:
-
为
NilClass添加显式模式匹配是否有效? -
NilClass和nil可以在这里互换使用,但我想要类似in variable: !NilClass -
读者:在
case声明中看到in而不是when,我感到很困惑。我很快发现这个 模式匹配 是在 v2.7 中引入的,而文档显然首先出现在 v3.0.0 中。如果这对您也很陌生,您可能会发现 this article 提供了有用的介绍。 -
IMO 你的第二个选项看起来不错
标签: ruby pattern-matching