How do I dynamically create a local variable in Ruby?

前端 未结 3 2114
闹比i
闹比i 2020-12-06 02:46

I am trying to dynamically create local variables in Ruby using eval and mutate the local-variables array. I am doing this in IRB.

eval \"t = 2\         


        
相关标签:
3条回答
  • 2020-12-06 03:01

    You could set instance variables like this:

    instance_variable_set(:@a, 2)
    @a
    #=> 2
    
    0 讨论(0)
  • 2020-12-06 03:06

    You have to synchronize the evaluations with the same binding object. Otherwise, a single evaluation has its own scope.

    b = binding
    eval("t = 2", b)
    eval("local_variables", b) #=> [:t, :b, :_]
    eval("t", b) # => 2
    b.eval('t') # => 2
    
    0 讨论(0)
  • 2020-12-06 03:13

    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
    
    0 讨论(0)
提交回复
热议问题