1

我进行了一个实验,试图了解单例是如何工作的。

我不明白为什么我们在类变量前面加上@@ 而不是@?如下所述,如果变量是与类定义内联创建的,则 self 定义为 Test,并且该变量是类变量对吗?然后我们可以在单例类定义中使用 attr_accessor 来访问它。initialize 中的@var 似乎有所不同,因为 self 在初始化时在上下文中设置为 t ,所以 var 在该上下文中属于 t ?

这一切都非常令人困惑,任何帮助将不胜感激。

class Test
  @var = 99
  attr_accessor :var

  def initialize
    @var = "Whoop" #if this is commented, pri doesn't print anything.
  end

  def pri
    puts @var
  end

  class << self
    attr_accessor :var
  end
end

t = Test.new
puts Test.var # Outputs 99
Test.var = 5
puts Test.var # Outputs 5
puts t.pri # Outputs Whoop
4

1 回答 1

3

if the variable is created inline with the class definition, self is defined as Test, and the variable is a class variable correct?

No. It is an instance variable of a class. It is not a class variable.

Instance variable is visible only to that instance. Class variable is visible to the class, other ancestry classes, and their instances.

  • @var defined in line 2 is defined for Test (which is an instance of Class class). It is not visible to ancestry classes of Test, nor to instances of them.
  • @@var is defined for Test as well as for its ancestry classes, as well as for their instances. They all share the same @@var.
  • @var defined in line 6 is defined for a certain instance of Test (which is not by itself Test). It is not visible to Test, nor to other instances of Test.
于 2013-05-28T06:36:10.923 回答