在没有空白“救援"块的情况下,让 Ruby 块/命令静默失败 [英] Having a Ruby block/command silently fail without a blank 'rescue' block
问题描述
说我想要运行一个调用,如果它失败了,也没什么大不了的;该程序可以毫无问题地继续.(我知道这通常是不好的做法,但想象一个假设的、快速的一次性脚本,而不是一个大型项目)
Say I want a call to be run, and if it fails, it's no big deal; the program can continue without a problem. (I know that this is generally bad practice, but imagine a hypothetical, quick one-off script, and not a large project)
我被教导这样做的方式是:
The way I've been taught to do this was:
begin
thing_to_try
rescue
# awkward blank rescue block
end
next_thing
当然,还有其他方法可以做到这一点,包括使用 ensure
和类似的东西.但是有没有办法让方法调用/块在没有混乱的空白块的情况下静默失败?
Of course, there are other ways to do this, including using ensure
and things like that. But is there a way to get a method call/block to silently fail without a messy blank block?
推荐答案
这样的方法很有帮助.
def squelch(exception_to_ignore = StandardError, default_value = nil)
yield
rescue Exception => e
raise unless e.is_a?(exception_to_ignore)
default_value
end
您可以在 class Object
中定义此方法以实现普遍可用性.
You might define this method inside class Object
for universal availability.
然后你可以写:
squelch { foo } || squelch { bar }
采用这种方法的真正优势是您可以使用多行块,因为内联 rescue
只能用于单个语句.
The real advantage to having this approach is you can use multiline blocks, since inline rescue
can only be used on a single statement.
这篇关于在没有空白“救援"块的情况下,让 Ruby 块/命令静默失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!