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)
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.
How can I eval two blocks of code and maintain local variables between them?
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.