Ruby インスタンス変数とクラス変数の簡単な使い方

  • 作成日 2021.10.04
  • 更新日 2022.08.02
  • Ruby
Ruby インスタンス変数とクラス変数の簡単な使い方

Rubyで、モジュールの簡単な使い方を記述してます。rubyのバージョンは2.7.2を使用してます。

環境

  • OS windows10 pro 64bit
  • ruby 2.7.2p137

インスタンス変数とクラス変数

インスタンス変数とクラス変数の違いは、以下の通りです。

  • インスタンス変数 : インスタンスごとに値が変わる
  • クラス変数 : インスタンスごとの値は同じ

インスタンス変数

実際にインスタンスを2つ生成して、インスタンス変数を利用してみます。
インスタンス変数は、変数の前に「@」を前に付けて定義します。

class Hoge
  def initialize(str)
    @name = str
  end

  def disp
    p @name
  end
end

hoge1 = Hoge.new("tanaka")
hoge2 = Hoge.new("ishibashi")

hoge1.disp # tanaka
hoge2.disp # ishibashi

hoge1とhoge2の値が異なることが確認できます。また、クラスメソッドからはアクセスできません。

class Hoge
  def initialize(str)
    @name = str
  end

  # クラスメソッドからアクセス
  def self.disp
    p @name
  end
end

Hoge.disp
# nil

クラス変数

次にクラス変数を定義してみます。
クラス変数は、変数の前に「@@」をつけて定義します。

class Hoge
  @@num = 0

  def disp
    @@num += 1
    p @@num
  end
end

hoge1 = Hoge.new

hoge1.disp # 1
hoge1.disp # 2

hoge2 = Hoge.new

hoge2.disp # 3
hoge2.disp # 4

クラス変数は、インスタンスが異なっても、値が共有されます。

クラスメソッドからも利用できます。

class Hoge
  @@num = 0

  def self.disp
    @@num += 1
    p @@num
  end
end

Hoge.disp # 1

継承先で変更されても、共有されます。

class Hoge
  @@num = 0

  def disp
    @@num += 1
    p @@num
  end
end

class Foo < Hoge
  def chnum
    @@num = 10
    p @@num
  end
end

foo = Foo.new

foo.chnum # 10

hoge = Hoge.new

hoge.disp # 11

attr_accessor

インスタンス変数は、「attr_accessor」を使用して定義することも可能です。

class Hoge
  attr_accessor :name, :age
end

hoge = Hoge.new

hoge.name = "tanaka"
hoge.age = 20

p hoge.name # "tanaka"
p hoge.age # 20