LoginSignup
0
0

More than 3 years have passed since last update.

[ruby]クラス変数、インスタンス変数の違い

Posted at

初めに

簡単にアウトプットさせてもらいます

クラス変数とは

クラス変数とはそのクラス内で定義された変数であり、@@から始まる変数となります。

インスタンス変数とは

インスタンス変数とはそのクラスのインスタンスで使用できる変数です。@から始まる変数となります。

クラス変数
class Muscle
  @@name = "大胸筋が歩いてる!!"

  def initiallize
    @@name
  end

  def workout
    puts @@name
  end
end

muscle = Muscle.new
muscle.workout

#実行結果
#大胸筋が歩いてる!!
インスタンス変数
class Muscle

  def initialize(name)
    @name = name
  end

  def workout
    puts "#{@name}"
  end

end

muscle = Muscle.new("大胸筋が歩いてる!!")
muscle.workout

#実行結果
#大胸筋が歩いてる!!

結果としてクラス変数と同じですが、インスタンス変数に値が入るのはインスタンス生成時です。

まとめ

インスタンス変数とクラス変数の違いは、インスタンス毎に値が固有であるか否か

0
0
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
0