LoginSignup
43

More than 3 years have passed since last update.

ローカル変数・インスタンス変数・クラス変数の違い(Ruby)

Last updated at Posted at 2019-06-23

各変数の使い方が分からなかったので備忘録として記します。
間違い等ありましたら、コメントいただけると嬉しいです!

ローカル変数

ローカル変数は、使用できる範囲(スコープ)が他の変数よりも限られている。
メソッドやブロック内で変数を定義した場合は、そのメソッドやブロック内で有効となる。
定義は、メソッド、ブロック内外で可能。
メソッド内(ブロック内)で使用できる変数。

ローカル変数
 class Person
  def greeting(name)
    personal_name = name             ←ローカル変数の定義
    "My name is #{personal_name}"
  end
 end

 person = Person.new('Taro')
 person.greeting  
 #=> "My name is Taro" 

注意点: メソッド内でローカル変数を定義した場合は、そのメソッド内で=を使用して引数を代入しないと、エラーが帰ってくる。(下記のような感じ!)

error-example
 class Person
   def initialize(name)
     personal_name = name
   end

   def greeting
     "My name is #{personal_name}"
   end
 end

 person = Person.new('Taro')
 person.greeting
 #=> Name error: undefined local variable or method "personal_name"・・・・

インスタンス変数

同じオブジェクト内(同クラス内)で共有可能な変数のこと
変数名に「@」をつける

インスタンス変数
 class Person
   def initialize(name)
     @personal_name = name         ←インスタンス変数の定義
   end

   def greeting
     "My name is #{@personal_name}"
   end
 end
 person = Person.new('Taro')
 person.greeting  
 #=> "My name is Taro" 

クラス変数

同じクラス内の全てのインスタンスメソッド内や継承されたクラス内(そのインスタンスメソッド内)で使用できる変数
変数名に「@@」をつける

クラス変数
 class Person                           
   @@personal_name = 'Taro'            ←クラス変数の定義

   def greeting
     @@personal_name
   end
 end

 class Personname < Person
   def name
     @@personal_name
   end
 end

 person = Person.new
 personname = Personname.new

 person.greeting  
 #=> "Taro" 

 personname.name
 #=> "Taro" 

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
43