在代码评估之间维护局部变量 [英] Maintaining local variables between eval of code

查看:66
本文介绍了在代码评估之间维护局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Ruby代码:

Consider the following Ruby code:

class Foo
  def bar; 42; end
  def run(code1,code2)
    binding.eval(code1,'c1')
    binding.eval(code2,'c2')
  end
end

Foo.new.run "x=bar ; p x", "p x"

目的是动态评估某些代码-创建局部变量-然后运行有权访问这些变量的其他代码.结果是:

The intent is to dynamically evaluate some code—which creates local variables—and then run additional code that has access to those variables. The result is:

c2:1:in `run': undefined local variable or method `x' for #<Foo:…> (NameError)

请注意,仅当eval更改了绑定时,上述内容才有效,仅当修改现有局部变量而不创建新变量时,该操作才会生效.我不一定需要(或希望)每次运行都使外部绑定发生突变,我只需要能够访问先前的绑定以进行后续代码评估.

Note that the above would only work if the eval mutated the binding, which it only does when modifying existing local variables, not creating new variables. I do not necessarily need (or want) each run to mutate the outer binding, I just need to be able to access the previous binding for subsequent code evaluations.

如何评估两个代码块并在它们之间维护局部变量?

出于好奇,它的实际应用是一个自定义工具,它可以执行脚本文件,然后放入REPL.我希望REPL可以访问脚本文件创建的所有局部变量.

For the curious, the real-world application of this is a custom tool that can execute a script file and then drop into a REPL. I want the REPL to have access to all local variables created by the script file.

推荐答案

您需要存储Binding并重新使用同一内容.如果您反复调用binding(即使在相同范围内),您将获得一个新的绑定.因此,对于演示功能,我们可以执行以下操作:

You need to store the Binding and re-use the same one. If you call binding repeatedly—even in the same scope—you will get a new binding. So, for the demo function, we can do this:

class Foo
  def initialize; @b = binding; end
  def bar; 42; end
  def run(code)
    @b.eval( code, '(yourcode)' )
  end
end

f = Foo.new
f.run "x=bar ; p x"  #=> 42
f.run "p x"          #=> 42

这篇关于在代码评估之间维护局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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