我想这样做的红宝石:在ruby中是否有begin ... rescue ... end(异常块)的功能版本?
safe_variable = begin
potentially_nil_variable.foo
rescue
some_other_safe_value
end
...和处理异常块(开始/救援/侧)作为功能/块。这不符合书面规定,但有没有办法得到类似的结果?
NB什么我实际上做的是这样的,它的工作原理,但IMO丑:
begin
safe_variable = potentially_nil_variable.foo
rescue
safe_variable = some_other_safe_value
end
UPDATE
我想我打的Ruby语法一个角落的情况。我实际上做的是这样的:
object_safe = begin potentially_nil_variable.foo
rescue ""
end
错误是class or module required for rescue clause
。可能它认为""
应该是异常结果的占位符。
你的第一个例子应该工作作为书面,其实 - 你得到什么错误? – 2010-05-04 21:31:38
奇怪的是,功能版本似乎没有出现在任何地方的红宝石文档。 – 2010-05-04 21:52:44