Let’s look at this code:
How the result will look? Of course you’ll never see
"two", but what about
Even you return from a function without exceptions,
ensure gets executed.
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.
Every time execution leaves
ensure gets executed no matter what: exception, return, next, break, etc.