Ruby1.9でwith

map が面倒なので DelegateMap - まめめもに触発されて。

テストコード

require "with"
class A
  attr_accessor :ins
  def test
    self.ins = "instance variable"
    lo = "local variable"
    with(["target variable"]) do
      # sorry can't use self...
      p ins
      p lo
      p at(0)
    end
  end
end

a = A.new
a.test

結果

"instance variable"
"local variable"
"target variable"

with.rbのソース

class Object
  private
  def with(target, *args, &block)
    WithDelegate.new(self, target).instance_exec(*args, &block)
  end
end
class WithDelegate<BasicObject
  def initialize(aself, target)
    @aself = aself
    @target = target
  end
  def method_missing(mhd, *args, &blk)
    if @target.public_methods.include? mhd then
      @target.public_send(mhd, *args, &blk)
    else
      @aself.send(mhd, *args, &blk)
    end
  end
end