这部分工作:
class Example1
@@var1= "var1 in the Example1"
def get_var1
@@var1
end
end
example1 = Example1.new
example1.get_var1
# => "var1 in the Example1"
但如果我尝试特征类:
def example1.get_var1
@@var1
end
example1.get_var1
# NameError: uninitialized class variable @@var1 in Object
# from (pry):128:in `get_var1'
Ruby 查找@@var1
而Object
不是Example
.
我在 Ruby 1.9.3 和 2.0 中测试了这段代码,结果相同。
为什么会这样?
第二件事,我们能不能把它关掉(这样example.get_var1
就不会在 Object 中寻找类变量了)?