Change Block Binding Without Eval?

陌路散爱 提交于 2019-12-09 23:00:42

问题


I realize that you can change the binding of a block using instance_eval

class Foo
  def bar &block
    instance_eval &block
  end
end

Foo.new.bar { self } # returns the instance

But some built in methods accept blocks and in that case it doesn't seem possible to change the binding of the block without messing with the internals of the built in method.

class Foo
  def enum &block
    Enumerator.new &block
  end
end

Foo.new.enum { self }.each {} # returns main!!!

Is there a way around this?


回答1:


You can work around it this way:

class Foo
  def enum &block
    Enumerator.new do |*args|
      instance_exec *args, &block
    end
  end
end

But I'm confident that you cannot change the binding of an existing Proc short of instance_eval/instance_exec-ing it.



来源:https://stackoverflow.com/questions/11587050/change-block-binding-without-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!