I have a bunch of links I need to build on page, links that are a modification to the current path. I wanted to be able to do my modifications and return the modified path (@updated_path) without changing the original path variable (@path).
This isn’t difficult stuff, the only thing that I had to ponder on for a moment is how to get the updated path and reset it to the original state (@path.dup) in one nice little call.
This worked out nicely:
def updated_path
@updated_path
ensure
@updated_path = @path.dup
end
The updated_path method will return the old value and reset it afterward. Nice and simple, I like.

Hmmm … will @updated_path return an error? I thought ensure would only be fired if an exception was raised.
If it’s just that it could be nil then you could ||= …
Oh I think I understand … the first ref to @updated_path should be to the method call updated_path … then the ensure block will be executed if an exception is raised … nice!
Actually, the call to updated_path will return the value of @updated_path. The ensure statement will then reset @updated_path to the original value.
For instance:
new_path = add_key_value_to_path(‘miles’,'50′)
As add_key_value_to_path does it’s thing, it updates @updated_path. The last line in add_key_value_to_path is the updated_path call. This will correctly return the value that new_path should get and reset @updated_path. Ready for the next iteration.
No exceptions are involved. Ensure is being used for it’s order of execution.
Oh I see! The ensure block is run regardless — resetting @updated_path to @path.dup; but the changed @updated_path is returned from the call … very interesting albeit a bit confusing. It saves having to create tmp variables.