Created
August 2, 2009 05:55
-
-
Save kakra/159936 to your computer and use it in GitHub Desktop.
A ruby implementation of python's with statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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