Ruby 2.6.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Bindingクラス > local_variable_set
local_variable_set(symbol, obj)
[permalink][rdoc]引数 symbol で指定した名前のローカル変数に引数 obj を設定します。
def foo
a = 1
bind = binding
bind.local_variable_set(:a, 2) # set existing local variable `a'
bind.local_variable_set(:b, 3) # create new local variable `b'
# `b' exists only in binding
p bind.local_variable_get(:a) # => 2
p bind.local_variable_get(:b) # => 3
p a # => 2
p b # => NameError
end
このメソッドは以下のコード(ただし、obj が Ruby のコードで出力される場合)と同様の動作をします。
binding.eval("#{symbol} = #{obj}")
[SEE_ALSO] Binding#local_variable_get, Binding#local_variable_defined?