10

evalローカル変数配列を使用してRubyでローカル変数を動的に作成し、変更しようとしています。私はIRBでこれをやっています。

eval "t = 2"
local_variables # => [:_]
eval "t"
# => NameError: undefined local variable or method `t' for main:Object
local_variables << "t".to_sym # => [:_, :t]
t
# => NameError: undefined local variable or method `t' for main:Object
4

3 に答える 3

16

評価を同じバインディング オブジェクトと同期する必要があります。それ以外の場合、単一の評価には独自のスコープがあります。

b = binding
eval("t = 2", b)
eval("local_variables", b) #=> [:t, :b, :_]
eval("t", b) # => 2
b.eval('t') # => 2
于 2013-07-24T19:13:06.990 に答える
12

You have to use the correct binding. In IRB for example this would work:

irb(main):001:0> eval "t=2", IRB.conf[:MAIN_CONTEXT].workspace.binding
=> 2
irb(main):002:0> local_variables
=> [:t, :_]
irb(main):003:0> eval "t"
=> 2
irb(main):004:0> t
=> 2
于 2013-07-24T19:23:46.167 に答える
8

次のようにインスタンス変数を設定できます。

instance_variable_set(:@a, 2)
@a
#=> 2
于 2013-07-24T19:13:49.183 に答える