【发布时间】:2012-05-22 14:14:32
【问题描述】:
我从this tutorial 看到了以下示例:
class Song
@@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
"This song: #@plays plays. Total #@@plays plays."
end
end
s1 = Song.new("Song1", "Artist1", 234) # test songs
s2 = Song.new("Song2", "Artist2", 345)
puts s1.play
puts s2.play
puts s1.play
puts s1.play
@@plays 是否只能在 Song 类中礼貌地访问? This commentary 提出了不推荐使用类变量的观点。是不是 b/c 它们在日常使用中通常不需要,并且在使用时会产生很多调试问题?
【问题讨论】:
标签: ruby class-variables