Ensure you understand ensure
rubyLet’s look at this code:
How the result will look? Of course you’ll never see "two"
, but what about "ensure"
?
Even you return from a function without exceptions, ensure
gets executed.
Another example:
And let’s look at result:
It was very surprising for me in a contrast with Ruby’s “least surprise principle”. But this is how it works:
Marks the final, optional clause of a begin/end block, generally in cases where the block also contains a rescue clause. The code in the ensure clause is guaranteed to be executed, whether control flows to the rescue block or not.
Conclusion
Every time execution leaves begin
block, ensure
gets executed no matter what: exception, return, next, break, etc.