如何为Ruby类的Singleton实例定义类变量?

时间:2019-04-01 10:56:29

标签: ruby

我们如何为一个类的单例实例定义一个类变量?

将把Ruby的类变量放在哪里?类变量的位置取决于什么?范围,词法上下文还是当前类?

class C
    class << self
        @@c = 1
    end
end
# C.class_variables => [:@@a]
# Why the class variables belong to C, instead of singleton instance of C?

class D
end
class << D
    @@d = 1
end
# Object.class_variables => [:@@d]
# warning: class variable access from toplevel
# Why the class variables belong to Object, instead of class D or singleton class of class D?

# How Ruby decide why to put the class variables?

1 个答案:

答案 0 :(得分:0)

对于类C,似乎在C的单例类中定义类变量等同于在C上定义相同的类变量。

class C
  @@a = 0
  class << self
    @@c = 1
  end
end

class D < C
end

C.class_variables
  #=> [:@@a, :@@c] 
D.class_variables
  #=> [:@@a, :@@c] 
C.singleton_class.class_variables
  #=> [] 
D.singleton_class.class_variables
  #=> [] 

D.class_variable_get(:@@a)
  #=> 0 
D.class_variable_set(:@@a, 2)
  #=> 2 
D.class_variables
  #=> [:@@a, :@@c] 
C.class_variable_get(:@@a)
  #=> 2 

D.singleton_class.class_variable_get(:@@c)
  #=> 1 
D.singleton_class.class_variable_set(:@@c, 3)
  #=> 3 
C.singleton_class.class_variable_get(:@@c)
  #=> 3