2014-05-03 143 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