Created
August 26, 2011 17:06
-
-
Save pasberth/1173871 to your computer and use it in GitHub Desktop.
apply.rb - Proc を binding を変えて実行します
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
| 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