确定开始块的值是多少? [英] How is the value of a begin block determined?

查看:127
本文介绍了确定开始块的值是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Ruby编程语言 p.164。


如果开始语句不会传播异常,那么值
的语句是
中最后一个表达式
的值开始 rescue else 子句

If a begin statement doesn't propagate an exception, then the value of the statement is the value of the last expression evaluated in the begin, rescue or else clauses.

但是我发现这个与开始块以及 else子句确认子句一致的行为。

But I found this behavior consistent with the begin block together with else clause and ensure clause.

以下是示例代码:

def fact (n)
  raise "bad argument" if n.to_i < 1
end

value = begin
  fact (1)
rescue RuntimeError => e
  p e.message
else
  p "I am in the else statement"
ensure
  p "I will be always executed"
  p "The END of begin block"
end

p value

输出是: / p>

The output is:

"I am in the else statement"
"I will be always executed"
"The END of begin block"
"I am in the else statement"
[Finished]

被评估为 else子句。这是不一致的行为,因为确保子句是执行的最后一个语句。

The value is evaluated to the else clause. This is inconsistent behavior as the ensure clause is the last statement executed.

有人可以解释开始块中发生了什么吗?

Could someone explain what's happening within the begin block?

推荐答案

我会将 begin / rescue / else / end 块的目标解释为:

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


  • 执行 begin 部分中的代码,然后执行 else 部分中的代码。

  • 如果 begin 部分出错,请执行 rescue 部分而不是 else 部分。

  • 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.

所以 rescue 部分或 else 部分将在尝试开始执行部分;所以有意义的是,其中一个将被用作整个块的值。

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"

但是:

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"

这篇关于确定开始块的值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆