确定开始块的值是多少? [英] How is the value of a begin block determined?
问题描述
根据 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 thebegin
,rescue
orelse
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 theelse
section. - If something goes wrong in the
begin
section, execute therescue
section instead of theelse
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屋!