With Statement in Ruby

One of the things that I do enjoy about Ruby is the ability to use blocks to synthesize control structures that may be missing. For instance, I'm a big fan of python's with statement. Through a combination of guerilla patching and blocks, the with statement can easily be added to the ruby language as a library.

require 'thread'

class Mutex
    def enter
        lock
    end

    def exit
        unlock
    end
end

class IO
    def enter
        return self
    end

    def exit
        close
    end
end

class ContextManager
    def enter
    end

    def exit
    end
end

def with(resource)
    begin
        yield(resource.enter())
    ensure
        resource.exit()
    end
end

This implementation allows for such beautiful usage as:

require 'thread'
require 'with_statement'

with(File.open("hello.txt")) {|f|
    puts f.read()
}

lock = Mutex.new
with(lock){
    puts "Yay! Synchronized!"
}