8 ms·
> given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..": Note that there
by masklinn 14y ago
> given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..":
Note that there's a difference in the handling of exceptions: if an exception is triggered from the `with` block, it is intercepted, provided to __exit__ and can be silenced if needed or desired (by returning a truthy value). So a closer approximation would be:
def with r
r.__enter__
begin
yield(r)
rescue Exception => e
raise unless r.__exit__(e)
else
r.__exit__(nil)
end
end