2014-05-03 146 views
0

我有这样的代码:递增类变量

class Person 
    @@instance_count = 0 

    def initialize name 
    @name = name 
    @@instance_count += 1 
    end 
    def self.instance_count 
    p "Instances created - #{@@instance_count}" 
    end 
end 

person_1 = Person.new "first_name" 
person_2 = Person.new "second_name" 
person_3 = Person.new "third_name" 

Person.instance_count 

其输出"Instances created - 3"

我不明白,为什么在+=增量initialize@@instance_count不是每次创建一个新的实例变量的时间重置为0。每次创建新实例时@@instance_count未重置为0时发生了什么?

+0

因为只有一个该变量的实例。没有新的创建。可能你会将类变量('@@ var')与实例变量('@ var')混淆 –

回答

3

名称以'@'开头的变量是自我的实例变量。 实例变量属于对象本身。

@foobar 

类变量由类的所有实例共享并以'@@'开头。

@@foobar 

这里是源:http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants#Instance_Variables

EDIT
# This is a class 
class Person 
    @@instance_count = 0 

    # This is the class constructor 
    def initialize name 
    @name = name 
    @@instance_count += 1 
    end 

    def self.instance_count 
    @@instance_count 
    end 
end 

# This is an instance of Person 
toto = Person.new "Toto" 
# This is another instance of Person 
you = Person.new "Trakaitis" 

p Person.instance_count # 2 

@@instance_countclass variable它连接到类本身,而不是它的实例。它是类定义的一部分,例如方法。 假设它已创建并设置为0,一旦ruby解析了您的类代码。

当您使用newtoto = Person.new "Toto")创建此类的新实例时,将调用类构造函数。所以@name将被创建为新实例的本地变量,并且以前设置为0的@@instance_count将被识别并递增1