How do I dynamically create a local variable in Ruby?

前端 未结 3 2132
闹比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: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
    

提交回复
热议问题