How is the value of the starting block determined?

According to the Ruby Programming Language with .164.

If the operator begindoes not throw an exception, then the value of the operator is the value of the last expression evaluated in begin, rescueor else.

But I found this behavior compatible with the begin block along with the else and provide clause .

Here is a sample code:

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

Conclusion:

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

valueevaluated in the else section . This is inconsistent behavior, as the last statement provide .

Can someone explain what is going on in the starting block?

+5
source share
3

begin/rescue/else/end :

  • begin, else.
  • - begin, rescue else.

, rescue else begin; , .

, ensure.

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"
+4

, , ( ), , else . , .

0

In this case, a block beginis just a way of defining a section for which you can perform exception handling.

Remember that elsein this case it is launched if there are no exceptions, but ensurewill be executed regardless of the exceptions or their absence.

0
source

All Articles