Skip to content

Instantly share code, notes, and snippets.

@sunaot
Created October 14, 2014 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/6deed99f97b114b5982c to your computer and use it in GitHub Desktop.
Save sunaot/6deed99f97b114b5982c to your computer and use it in GitHub Desktop.
Ruby でクロージャのローカル変数を差し替え (たかのように錯覚させる) トリック
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
@sunaot
Copy link
Author

sunaot commented Oct 14, 2014

Proc#binding で取り出した Binding オブジェクトに local_variable_set してやって、その更新された binding でもって Proc#call をしたかったが、eval は文字列しかとれなかったのでついカッとなってやった。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment