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?

「変数」と「メソッドの名前」衝突時の挙動 を試すコード

Posted at

rubysilverの勉強をしてたら出てきた問題を備忘録に残しておきます!

大元のコードはこれ

hoge = 0
def hoge
  x = 0
  5.times do |i|
    x += 1
  end
  x
end
puts hoge

hoge = 0
ここで「ローカル変数 hoge」が定義される。
この時点では、hoge は ただの整数 0 を指している。

def hoge ... end
次に、グローバルなメソッド hoge が定義される。
Rubyでは「ローカル変数」と「メソッド」は名前が同じでも共存できる。

ただし!優先順位がある
・ローカル変数がすでに定義されていれば、そっちが優先される
・つまり、同じスコープで hoge と書いたら、メソッド呼び出しではなく「変数参照」と解釈される

x = 0
ローカル変数 x を 0 で初期化。
この x はメソッドの中だけで有効。メソッドが終わると消える。

5.times do |i| ... end
繰り返し構文。
• 5.times は「0 から 4 まで」の整数を順に i に渡しながら、ブロックを5回実行する。
• だから、ループ中での i は 0,1,2,3,4 となる。

x += 1
ループのたびに x を1増やしている。
x += 1 は x = x + 1 の短縮形。
ループの中の動き

  1. 初期値 x = 0
  2. i=0 → x=1
  3. i=1 → x=2
  4. i=2 → x=3
  5. i=3 → x=4
  6. i=4 → x=5

puts hoge
ここで「メソッドを呼ぶのかな?」と思いきや…
すでに hoge = 0 でローカル変数があるので、メソッド hoge は呼ばれず、ローカル変数 hoge が参照される。

つまり出力結果は「0」

もし変数がなかったら?

def hoge
  x = 0
  5.times { x += 1 }
  x
end

puts hoge

この場合はメソッド hoge が呼ばれるので、
ループで x が 5 回インクリメントされ、最終的に 5 が返って出力される。つまり出力結果は「5」

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?