From: Josh Cheek Date: 2011-11-15T08:53:48+09:00 Subject: Re: Binding#with --0016364d237fadf3ff04b1ba940c Content-Type: text/plain; charset=ISO-8859-1 On Mon, Nov 14, 2011 at 10:41 AM, Intransition wrote: > Well, this seems to work: > > # > def with(_hash, &_yield) > _hash = (_hash || {}).to_hash > code = <<-END > define_method(:_with) do |#{_hash.keys.join(',')}| > binding > end > END > (class << self; self; end).class_eval(code) > b = _with(*_hash.values, &_yield) > (class << self; self; end).class_eval{ remove_method(:_with) } > return b > #eval("Proc.new{ |#{_hash.keys.join(',')}| binding > }").call(*_hash.values) > end > > But alas, now I am loosing the context of original binding. Why is that? I > thought define_method kept closure. > > Not sure what you mean, it seems to work for me: class Binding def with(_hash={}, &_yield) singleton_class.class_eval(<<-CODE) define_method :_with do |#{_hash.keys.join(',')}| binding end CODE bnd = _with(*_hash.values, &_yield) singleton_class.class_eval { remove_method :_with } bnd end end RUBY_VERSION # => "1.9.3" binding.with(:a => 10) { |x| x + x }.eval('yield a + 5') # => 30 --0016364d237fadf3ff04b1ba940c--