我希望能够运行字符串的eval函数来定义本地变量和常量。我想在不同的命名空间中执行此操作。我可以使用本地变量来完成此操作,但无法使用常量。是否有一种方法可以修改下面的NameSpaces模块,以便在一个绑定/命名空间中定义的常量不会被另一个绑定/命名空间看到?
# Example run under ruby 1.9.1
module NameSpaces
def self.namespace(namespace)
return binding
end
end
b1 = NameSpaces.namespace("b1")
b2 = NameSpaces.namespace("b2")
# Set a 'x', then check to make sure its still set in the scope of 'b1'
puts b1.eval("x = 1") # => 1
puts b1.eval("x") # => 1
# Check to make sure 'x' is NOT set in the scope of 'b2'
begin
puts b2.eval("x") # NameError exception expected here
rescue Exception => e
puts e.to_s # => undefined local variable or method `x'
# for NameSpaces:Module (THIS IS AS EXPECTED.)
end
# Set constant 'C' and do the same checks
puts b1.eval("C = 1") # => 1
puts b1.eval("C") # => 1
# Check to make sure 'C' is NOT set in the scope of 'b2'
begin
puts b2.eval("C") # (I DON'T GET AN EXCEPTION. NOT AS I HAD HOPED FOR.)
rescue Exception => e
puts e.to_s
end
非常感谢您的关注。我遇到了非常困难的问题。
@namespace =
开头的那一行应该改为@namespace = (@spaces.id[id] ||= Module.new.class_eval("binding"))
。抱歉,我会修改我的回答。 - Alex D