BasicObject.class_eval do
def instance(ins)
eval "@#{ins}=#{ins}", binding
end
end
是有问题的代码。我想要它做的是在下面的代码中,在类 Foo 中创建一个新的实例变量 bar。运行此代码后得到的结果:
class Foo
bar = 3
end
Foo.instance(:bar)
是:
NameError: undefined local variable or method `bar for Foo:Class
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `eval'
from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'
为什么会这样。