簡體   English   中英

紅寶石中是否有begin…rescue…end(異常塊)的功能版本?

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

我想在Ruby中做這樣的事情:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

...並將異常塊(開始/救援/結束)視為功能/塊。 這不能按書面規定工作,但是有沒有辦法得到類似的結果?

請注意,我實際上正在做的是這個,但是可以,但IMO很難看:

begin
  safe_variable = potentially_nil_variable.foo
rescue
  safe_variable = some_other_safe_value
end

更新

我想我在ruby語法上碰到了一個極端案例。 我實際上在做的是:

object_safe = begin potentially_nil_variable.foo
rescue ""
end

錯誤是class or module required for rescue clause 它可能認為""應該是異常結果的占位符。

您擁有的表格應該可以工作:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

較短的形式:

safe_variable = this_might_raise rescue some_other_safe_value

如果僅避免使用nil ,則可以研究ActiveRecord的try

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

我知道的將消息發送到可能為零的對象的最實用的方法是andand 對於nil, andand返回一個對象,無論您發送什么消息,該對象都會簡單地返回nil。 對於其他對象,它將返回原始對象。 幾乎所有的事情都比破例更有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM