There are no proper equivalents to the defer
statement in ruby, however if you want to make sure that a specific code block is executed, you can use the ensure
statement. The difference is that you cannot stack code blocks like defer does, but the result is the same.
In a block
begin
# ...
ensure
# This code will be executed even if an exception is thrown
end
In a method
def foo
# ...
ensure
# ...
end
Object#ensure 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.