Created
October 14, 2014 17:50
-
-
Save sunaot/6deed99f97b114b5982c to your computer and use it in GitHub Desktop.
Ruby でクロージャのローカル変数を差し替え (たかのように錯覚させる) トリック
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
def e &blk | |
s = Struct.new(:a,:b,:c).new(1,2,3) | |
s.instance_eval(&blk) | |
end | |
def foo | |
e { a + b + c } | |
end | |
puts foo #=> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Proc#binding で取り出した Binding オブジェクトに local_variable_set してやって、その更新された binding でもって Proc#call をしたかったが、eval は文字列しかとれなかったのでついカッとなってやった。