Ensure Ruby returns the correct value
Ruby has implicit returns for any possible block that I can think of, except ensure
. There might be more, but this is the only one that I can think of now.
So in order to return something from inside the ensure
block we must use the return
reserved word explicitly. Check this out:
def check_this_out
yield if block_given?
:ok
rescue
:error
ensure
:ensured
end
irb()> check_this_out { "should work" }
=> :ok
irb()> check_this_out { raise "should fail" }
=> :error
As we can see even though the ensure
code runs on all calls it does not return :ensured
.
Here's the code with the explicit return
:
def check_this_out_explicit_ensure_return
yield if block_given?
:ok
rescue
:error
ensure
return :ensured
end
irb()> check_this_out_explicit_ensure_return { "should work" }
=> :ensured
irb()> check_this_out_explicit_ensure_return { raise "should fail" }
=> :ensured
Tweet