class Foo
@@cc = 0
def self.inc
@c = @c || 0
@c += 1
@@cc += 1
p "@c=#{@c}, @@c=#{@@cc}"
end
def dec
@c = @c || 0
@c -= 1
@@cc-= 1
p "@c=#{@c}, @@c=#{@@cc}"
end
end
執行結果:
Foo.inc
=>"@c=1, @@c=1"
Foo.inc
=>"@c=2, @@c=2"
foo = Foo.new
foo.dec
=>"@c=-1, @@c=1"
Foo.inc
=>"@c=3, @@c=2"
foo.dec
=>"@c=-2, @@c=1"
以上結果~ @變數在 instance method 與 class method 是不同的.
但 @@變數是相同的.
沒有留言:
張貼留言