class Foo
def self.run(n,code)
foo = self.new(n)
@env = foo.instance_eval{ binding }
@env.eval(code)
end
def initialize(n)
@n = n
end
end
Foo.run( 42, "p @n, defined? foo" )
#=> 42
#=> "local-variable"
Run Code Online (Sandbox Code Playgroud)
上面的示例程序旨在评估Foo实例范围内的任意代码.它就是这样,但绑定被code方法中的局部变量"污染"了.我不希望foo,n或者code对eval'd代码可见.所需的输出是:
#=> 42
#=> nil
Run Code Online (Sandbox Code Playgroud)
如何创建(a)在对象实例范围内的绑定,但(b)没有任何局部变量?
我创建绑定而不是仅使用绑定的原因instance_eval(code)是,在实际使用中我需要保持绑定以供以后使用,以保留在其中创建的局部变量.
就这样?或者我在这里错过了一些重要的事情?
class Foo
attr_reader :b
def initialize(n)
@n = n
@b = binding
end
def self.run(n, code)
foo = self.new(n)
foo.b.eval(code)
end
end
Foo.run(42, "p @n, defined?(foo)")
# 42
# nil
Run Code Online (Sandbox Code Playgroud)
或者将其进一步向下移动以获得更少的上下文
class Foo
def initialize(n)
@n = n
end
def b
@b ||= binding
end
def self.run(n, code)
foo = self.new(n)
foo.b.eval(code)
end
end
Foo.run(42, "p @n, defined?(foo), defined?(n)")
# 42
# nil
# nil
Run Code Online (Sandbox Code Playgroud)