LoginSignup
0
0

More than 3 years have passed since last update.

ローカル変数とインスタンス変数の違い

Posted at

ローカル変数とインスタンス変数の違い

ローカル変数
その場限りの一時的な変数。
メソッド内で定義したローカル変数はそのメソッドの中でしか使えない。

インスタンス変数
オブジェクトの保持する変数。
オブジェクトのどのメソッド内でも使用できる

ローカル変数numberを使ってメソッドを呼び出す

myclass.rb
class Myclass
 def method_1
  number = 100
 end

 def method_2
  number
 end
end
>object = Myclass.new
>object.method_1
=> 100

>object.method_2
Traceback(most recente call last):
NameError (undifined...)

method_2ではエラーが返ってきています。
つまりmethod_2ではmethod_1で使ったnumberは使えない状態だということです。

インスタンス変数@numberを使う

myclass.rb
class Myclass
 def method_1
  @number = 100
 end

 def method_2
  @number
 end
end
>object = Myclass.new
>object.method_1
=> 100

>object.method_2
=> 100

無事2つとも100という値が返っています。
つまりmethod_1とmethod_2では同じ@numberが使えているということです。

まとめ

ローカル変数は1つのメソッドの中で一時的に使うデータを参照するために使用する。
一方で、インスタンス変数は特定のオブジェクト内で使いまわしたり、オブジェクトに属するデータとして外部からゲッターを利用するために使用する。

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