Skip to content

Instantly share code, notes, and snippets.

@taichi-ishitani
Created April 13, 2019 04:47
Show Gist options
  • Save taichi-ishitani/81747399d9039bb1e0020319514ceb45 to your computer and use it in GitHub Desktop.
Save taichi-ishitani/81747399d9039bb1e0020319514ceb45 to your computer and use it in GitHub Desktop.
Proc をあるコンテキスト上で実行する
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