2

这部分工作:

 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 查找@@var1Object不是Example.

我在 Ruby 1.9.3 和 2.0 中测试了这段代码,结果相同。

为什么会这样?
第二件事,我们能不能把它关掉(这样example.get_var1就不会在 Object 中寻找类变量了)?

4

1 回答 1

7

看起来类变量查找的词法范围有点古怪。据我所知,因为你不在里面

class Example1
end

块,ruby 不会在你的类中查找 @@var ,而是从 Object 中查找。如果你想从你的班级明确地得到它,你可以这样做:

def example1.get_var
    self.class.class_variable_get(:@@var1)
end

我在寻找答案时偶然发现了https://www.ruby-forum.com/topic/1228428 。他们在谈论 1.8.7,但它似乎也适用于更高版本。

于 2014-07-01T13:51:11.400 回答