How is the value of a begin block determined?

微笑、不失礼 提交于 2019-12-05 08:37:57

I'd interpret the goal of the begin/rescue/else/end block as:

  • Execute the code in the begin section, and then the code in the else section.
  • If something goes wrong in the begin section, execute the rescue section instead of the else section.

So either the rescue section or the else section will be executed after trying the begin section; so it makes sense that one of them will be used as the whole block's value.

It's simply a side effect that the ensure section will always be executed.

val = begin
  p "first"; "first"
rescue => e
  p "fail"; "fail"
else
  p "else"; "else"
ensure
  p "ensure"; "ensure"
end

val # => "else"
# >> "first"
# >> "else"
# >> "ensure"

But:

val = begin
  p "first"; "first"
  raise
rescue => e
  p "fail"; "fail"
else
  p "else"; "else"
ensure
  p "ensure"; "ensure"
end

val # => "fail"
# >> "first"
# >> "fail"
# >> "ensure"

I'm just guessing here, but as the purpose of a ensure block is to finalize any resources that may remain open (cleanup in other words), and so it makes sense that the logical value should be the result of the else statement. It makes sense to me that it is by design.

In this case the begin block is just a way of defining a section for which you may want to do exception handling.

Remember that else in this case runs if no exceptions occur, and ensure will run regardless of exceptions or a lack thereof.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!