Sim*_*ide 0 ruby functional-programming exception
我想在ruby中做这样的事情:
safe_variable = begin
potentially_nil_variable.foo
rescue
some_other_safe_value
end
Run Code Online (Sandbox Code Playgroud)
...并将异常块(开始/救援/结束)视为函数/块.这不起作用,但有没有办法得到类似的结果?
请注意,我实际上在做的是这个,但是IMO很丑陋:
begin
safe_variable = potentially_nil_variable.foo
rescue
safe_variable = some_other_safe_value
end
Run Code Online (Sandbox Code Playgroud)
UPDATE
我想我在ruby语法上遇到了一个问题.我实际上在做的是:
object_safe = begin potentially_nil_variable.foo
rescue ""
end
Run Code Online (Sandbox Code Playgroud)
错误是class or module required for rescue clause.可能它认为""应该是异常结果的占位符.
你有的形式应该工作:
safe_variable = begin
potentially_nil_variable.foo
rescue
some_other_safe_value
end
Run Code Online (Sandbox Code Playgroud)
更短的形式:
safe_variable = this_might_raise rescue some_other_safe_value
Run Code Online (Sandbox Code Playgroud)
如果你只是避免nil,你可以查看ActiveRecord的try:
safe_variable = potentially_nil_variable.try(:foo) || some_other_safe_value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |