0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ローカル変数とグローバル変数について(入門者)

Last updated at Posted at 2019-07-05

ローカル変数、グローバル変数

 ローカル変数とは、あるところで使われている変数名を別のところで使っても、違う変数として扱われるものである。一方グローバル変数とは、プログラム中のどこで使われていても、名前が同じであれば、必ず同じ変数として扱われるものである。

書き方

まず書き方として変数名は仮にaとすると、

ローカル変数: a
グローバル変数:$a

実際に動かす

index.rb
a = 0      #ローカル変数
$a = 0     #グローバル変数

require_revative "input"     #input.rbファイルを読み込む

# 出力結果
p a        # => 0
p $a       # => 1
input.rb
a = 1
$a = 1

まとめ

グローバル変数はプログラムのどこからでも書き換えることができるので、一般的には好まれない。また、ローカル変数は最初に何かを代入されたときに初期化され、初期化されていないローカル変数を参照しようとするとエラーがでる。

追記

以下のコメントで、scivolaさんにご指摘していただいた点で、

厳密にはローカル変数は初期化されていなくとも、代入式が__存在__していれば__宣言__される。

以下のコードをお借りすると、

if false
  a = 1
end

p a # => nil → エラーは出ない

代入式 a = 1は実行されず、初期化はされていない。しかし、宣言はされているのでエラーは出ない。また、宣言はされているが代入されていないローカル変数はnilになるとのこと。

scivolaさんご指摘あありがとうございました。

0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?