類變量是這樣的:類實例變量的正確用法
class Hello
@@x = 0
def self.counter
@@x
end
def initialize
@@x += 1
end
end
Hello.new
Hello.new
Hello.new
p Hello.counter
#=> 3
但類實例變量不:
class Goodbye
@x = 0
def self.counter
@x
end
def initialize
@x += 1
end
end
Goodbye.new
Goodbye.new
Goodbye.new
Goodbye.new
p Goodbye.counter
#=> Error
我在做什麼錯?我的印象是,類實例變量與類變量相同,只是沒有繼承問題......但是你如何使用它們(例如,像在我這裏發佈的代碼中那樣計算特定類的實例)?
的可能重複(http://stackoverflow.com/questions/3802540/difference-between-class-variables-和類實例變量) – 2014-09-28 09:51:57
沒有解釋爲什麼使用@@ x的代碼工作,並且與@x使用相同的代碼沒有(這就是爲什麼我問這個問題) – OldBoy 2014-09-28 09:56:52
關於'爲什麼這個代碼不工作的問題「關於SO的話題。 – 2014-09-28 09:58:29