Skip to content

Instantly share code, notes, and snippets.

@kakra
Created August 2, 2009 05:55
Show Gist options
  • Save kakra/159936 to your computer and use it in GitHub Desktop.
Save kakra/159936 to your computer and use it in GitHub Desktop.
A ruby implementation of python's with statement
# A ruby implementation of python's with statement
#
# not sure if this is semantically identical, it was meant as a small excercise
module WithStatement
def with(*objs)
raise "no block given" unless block_given?
options = objs.unshift! if objs.last.is_a? Hash
options = { :enter => :enter_with, :exit => :exit_with }.merge(options || {})
entered = 0
begin
# Initialize all objs with the given method (default: Object#enter_with)
objs.each { |obj| obj.send options[:enter]; entered += 1 }
yield *objs
ensure
# Ensure their appropriate exit methods are called in reverse order
# no matter if an exception was raised or not
objs[0...entered].reverse.each { |obj| obj.send options[:exit] }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment