Skip to content

Instantly share code, notes, and snippets.

@pocke
Created December 18, 2016 10:48
Show Gist options
  • Save pocke/59adea1134bccedf5fbff42ee396093b to your computer and use it in GitHub Desktop.
Save pocke/59adea1134bccedf5fbff42ee396093b to your computer and use it in GitHub Desktop.
def foo
tap do
$_ = 3
p $_
end
p $_
end
foo
puts '-------------'
def bar
tap do
_ = 3
p _
end
p _
end
bar
@pocke
Copy link
Author

pocke commented Dec 18, 2016

3
3
-------------
3
/tmp/tmp.od5Xrii7ZS/test.rb:17:in `bar': undefined local variable or method `_' for main:Object (NameError)
	from /tmp/tmp.od5Xrii7ZS/test.rb:19:in `<main>'


@pocke
Copy link
Author

pocke commented Dec 18, 2016

https://docs.ruby-lang.org/ja/latest/class/Kernel.html#V__

この変数はローカルスコープかつスレッドローカルです。

https://docs.ruby-lang.org/ja/latest/doc/spec=2fvariables.html#global

ローカルスコープ

通常のローカル変数と同じスコープを持ちます。つまり、 class 式本体やメソッド本体で行われた代入はその外側には影響しません。 プログラム内のすべての場所において代入を行わずともアクセスできることを除いて、通常のローカル変数と同じです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment