[Ruby]Binding#local_variable_set

local_variable_set(symbol, obj) https://docs.ruby-lang.org/ja/latest/method/Binding/i/local_variable_set.html

動的に変数を設定できるメソッド。 引数symbolの名前で変数を定義し、objを変数の値としてセットする。

# 設定ファイルを元に動的に変数を定義する
def configure_variables(config)
  b = binding
  config.each do |key, value|
    b.local_variable_set(key, value)
  end
  eval('puts "Configured: #{foo}, #{bar}"', b)
end

config = { foo: 'Hello', bar: 'World' }
configure_variables(config)
# => "Configured: Hello, World"

Twitterで検索するとメタプロ好きな人たちがlocal_variable_setはいいぞって言っている姿が観測できる https://x.com/search?q=local_variable_set&src=typed_query