类的实例变量是对象的类变量?

时间:2017-11-04 00:54:29

标签: ruby

给出这个例子:

class Pepe
   def self.test
     # this is a instance variable of a class
     @klass_var = 123
   end

   def instance_method
     # here self is an instance of Pepe, @@klass_var is the same than previous @klass_var ?
     @@klass_var
   end
end

为什么@@klass_var不一样?

1 个答案:

答案 0 :(得分:-3)

class Pepe
   @@klass_var = 345
   def self.test
     # this is a instance variable of a class
     @@klass_var = 123
   end

   def instance_method
     # here self is an instance of Pepe, @@klass_var is the same than previous @klass_var ?
     @@klass_var
   end
end

Pepe.new.instance_method # 345

Pepe.test # this sets @@klass_var

Pepe.new.instance_method # 123