LoginSignup
0
1

More than 3 years have passed since last update.

【備忘録】Ruby : クラス変数の使い方

Posted at
sample.rb

class Num
    @@num = 1
    #クラス変数
    #インスタンスメソッドからでもクラスメソッドからでもアクセス可能
    #異なるオブジェクトでも同じクラスであれば値は共有可能
    #あまり使われることはないらしい
    def increment
        @@num += 1
    end

    def decrement
        @@num -= 1
    end

    def num
        puts @@num
    end

    def self.num
        puts @@num
    end
end

foo = Num.new
foo.num #=> 1
foo.increment #+1
foo.num #=> 2
foo.decrement #-1
foo.num #=>1
foo.decrement #-1

fuga = Num.new
fuga.num #=>0
#新しいオブジェクトを作ったのにも関わらず、fooオブジェクトでの処理を引き継いでいる。
#引き継がない場合は 1 からスタートするはず。


0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1