Created
April 13, 2019 04:47
-
-
Save taichi-ishitani/81747399d9039bb1e0020319514ceb45 to your computer and use it in GitHub Desktop.
Proc をあるコンテキスト上で実行する
This file contains 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 call_on(context, *args, &block) | |
@__call_on__method__ ||= define_call_on_method | |
@__call_on__method__.bind(context).call(*args, &block) | |
end | |
private | |
def define_call_on_method | |
Module.new.module_exec(self) do |body| | |
define_method(:__call_on__, &body) | |
instance_method(:__call_on__) | |
end | |
end | |
end | |
o = Object.new | |
def o.foo | |
@bar ||= 3 | |
2 | |
end | |
b = proc { |baz, &qux| foo + @bar + baz + qux.call } | |
p b.call_on(o, 4) { 5 } | |
p b.call_on(o, 5) { 6 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment