简体   繁体   English

红宝石中是否有begin…rescue…end(异常块)的功能版本?

[英]Is there a functional version of begin…rescue…end (exception block) in ruby?

I'd like to do something like this in ruby: 我想在Ruby中做这样的事情:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

... and treat the exception block (begin/rescue/end) as a function/block. ...并将异常块(开始/救援/结束)视为功能/块。 This doesn't work as written, but is there a way to get a similar result? 这不能按书面规定工作,但是有没有办法得到类似的结果?

NB what I'm actually doing is this, which works but is IMO ugly: 请注意,我实际上正在做的是这个,但是可以,但IMO很难看:

begin
  safe_variable = potentially_nil_variable.foo
rescue
  safe_variable = some_other_safe_value
end

UPDATE 更新

I guess I hit a corner case on ruby syntax. 我想我在ruby语法上碰到了一个极端案例。 What I actually was doing was this: 我实际上在做的是:

object_safe = begin potentially_nil_variable.foo
rescue ""
end

The error was class or module required for rescue clause . 错误是class or module required for rescue clause Probably it thought that "" was supposed to be the placeholder for the exception result. 它可能认为""应该是异常结果的占位符。

The form you have should work: 您拥有的表格应该可以工作:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

A shorter form: 较短的形式:

safe_variable = this_might_raise rescue some_other_safe_value

If you're only avoiding nil , you can look into ActiveRecord's try : 如果仅避免使用nil ,则可以研究ActiveRecord的try

safe_variable = potentially_nil_variable.try(:foo) || some_other_safe_value

The most functional approach I know of for sending a message to an object that might be nil is something like andand . 我知道的将消息发送到可能为零的对象的最实用的方法是andand For nil, andand returns an object that will simply return nil no matter what message you send it. 对于nil, andand返回一个对象,无论您发送什么消息,该对象都会简单地返回nil。 For other objects, it returns the original object. 对于其他对象,它将返回原始对象。 And pretty much anything will be more efficient than mucking around with exceptions. 几乎所有的事情都比破例更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM