Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created August 26, 2011 17:06
Show Gist options
  • Select an option

  • Save pasberth/1173871 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1173871 to your computer and use it in GitHub Desktop.
apply.rb - Proc を binding を変えて実行します
class Proc
def apply(binding, *args)
binding.instance_variable_set :@args, args
binding.instance_eval do
def method_missing varname, *args, &blk
return if varname == :to_ary
if !args.empty? || blk
$temp_args = args
$temp_blk = blk
res = eval "#{varname} *$temp_args, &$temp_blk"
$temp_args = nil
$temp_blk = nil
else
res = eval "#{varname}"
end
res
end
end
binding.instance_exec(*args, &self)
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class TestApply < Test::Unit::TestCase
def setup
end
def a_binding(&blk)
i = 42
blk.apply binding, "hello"
end
def test_apply
a_binding { |string|
assert_equal i, 42
assert_equal string, "hello"
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment