Skip to content

Instantly share code, notes, and snippets.

@teslur
Last active September 11, 2021 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teslur/9c88168992c2ba9e3fc2c21ec5d4cf66 to your computer and use it in GitHub Desktop.
Save teslur/9c88168992c2ba9e3fc2c21ec5d4cf66 to your computer and use it in GitHub Desktop.
hoisting in debugger
require 'bundler/setup'
require 'debug'
def method_or_variable
'method'
end
if true
binding.break # (rdbg) p method_or_variable #=> nil
else
method_or_variable = 'variable'
end
def method_or_variable
'method'
end
if true
p method_or_variable #=> "method"
else
method_or_variable = 'variable'
end
@teslur
Copy link
Author

teslur commented Sep 11, 2021

通常のrubyプログラムとしてnormal.rbを実行すると、"method"が出力される。
この"method"を出力する位置にbinding.breakを仕込んだdebugger.rbを実行し、debug gem内でp method_or_variableを行うとnilが出力される。

下のローカル変数がhoistingを起こしていて、メソッド呼び出しよりもローカル変数が優先される結果、ローカル変数を参照している。
これは別にdebug gemだからじゃなくて、binding.irbでもbinding.pryでもなんならeval(:method_or_variable)でも同じことが起きる。

@teslur
Copy link
Author

teslur commented Sep 11, 2021

昔モチャモチャやったリポにも反映した。
hoistディレクトリ配下だけ反映。

https://github.com/teslur/method_or_variable

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