😎
[Bug #21049] Binding#local_variables から Numbered parameter などを削除する提案
[Bug #21049] Reconsider handling of the numbered parameters and "it" parameter in Binding#local_variables
-
Binding#local_variablesで Numbered parameter やitをサポートすべきかどうかを議論するチケット - モチベーションとしては現状だと以下のようにうまく処理できていない
# Binding#local_variables に本来含まれるべきではない Numbered parameter が含まれている
"foo".tap do
_1
"bar".tap do
p binding.local_variables #=> expected: [], actual: [:_1]
end
end
# Binding#local_variable_get で読み込み不可のパラメータが参照できてしまう
"foo".tap do
_1
"bar".tap do
p binding.local_variable_get(:_1) #=> expected: NameError, actual: "foo"
end
end
# Binding#local_variable_set で意図せず値を書き換えることができてしまう
"foo".tap do
p _1 #=> "foo"
binding.local_variable_set(:_1, "bar") # expected: NameError, actual: updates _1
p _1 #=> "bar"
end
- ここでは
Binding#local_variablesでのサポートを停止する提案がされている
"foo".tap do
_1
binding.local_variables #=> proposed: []
binding.local_variable_get(:_1) #=> proposed: NameError
end
- また Numbered parameter や
itを取得したい場合は専用の API を用意するとよい、とも提案しているBinding#numbered_parameters #=> [:_1, :_2, :_3, ...]Binding#numbered_parameter_get(:_1) #=> objBinding#numbered_parameter_defined?(:_1) #=> true or falseBinding#it_get #=> objBinding#it_defined? #=> true or false
-
_1が単純な変数ではなかったりitが特別な記号の場合と単純な変数(やメソッド)であるケースがあるのでこのあたり切り分けるのが大変そうみたいですね - matz がコメントしているんですが『最初の3つはすべて想定通り』『リアルベースのユースケースを探るとよい』と書いていますね
- なので特にこのチケットでは対応しないのかな?と思ったんですが最初の3つの例は
actualになるように対応されたみたいですね - Ruby 4.0 からは以下のように挙動が変わる
"foo".tap do
_1
"bar".tap do
p binding.local_variables
# Ruby 3.4 => [:_1]
# Ruby 4.0 => []
end
end
"foo".tap do
_1
"bar".tap do
p binding.local_variable_get(:_1)
# Ruby 3.4 => "foo"
# Ruby 4.0 => error: numbered parameter '_1' is not a local variable (NameError)
end
end
"foo".tap do
p _1 #=> "foo"
binding.local_variable_set(:_1, "bar")
# Ruby 3.4 => updates _1
# Ruby 4.0 => error: numbered parameter '_1' is not a local variable (NameError)
p _1 #=> "bar"
end
- ただ RubyMine ではデバッグ中に Numbered parameter の値を表示する機能があり、この変更によりそれらが表示できなくなった、みたいな困りごとも出てきているみたいですね
- このあたり含めて Ruby 4.0 では最終的にどうなるのか
Discussion