更改没有绑定的块绑定吗? [英] Change Block Binding Without Eval?

查看:56
本文介绍了更改没有绑定的块绑定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到您可以使用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?

推荐答案

您可以通过以下方式解决它:

You can work around it this way:

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

但是我相信,如果没有instance_eval/instance_exec,您将无法更改现有Proc的绑定.

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

这篇关于更改没有绑定的块绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆