2017-04-27 67 views
0

我已经为能够运行ruby脚本的软件做了一个基本的REPL。我希望能够在启动时将前一个范围的变量传递给REPL,这样我就可以轻松地调试我的代码。将Kernel.local_variables附加到绑定范围

def launchREPL(locals) 
    puts "\"Starting REPL...\"" 
    __b = binding #Evaluating in a binding, keeps track of local variables 
    __s = "" 
    __b.local_variables = locals ## <-- ERROR OCCURS HERE 
    bStartup = true 
    while bStartup || __s != "" 
     # If startup required skip evaluation step 
     if !bStartup 

      #Evaluate command 
      begin 
       __ret = __s + "\n>" + __b.eval(__s).to_s 
      rescue 
       __ret = __s + "\n> Error: " + $!.to_s 
      end 
      puts __ret 
     else 
      #REPL is already running 
      bStartup = false 
     end 

     #Read user input & print previous output 
     __s = Application.input_box(__ret,"Ruby REPL","") 
     __s == nil ? __s = "" : nil 
    end 
end 

以上是我启动REPL的代码。我的想法是,我可以这样做:

launchREPL(Kernel.local_variables) 

然后能够访问REPL中以前范围内的所有局部变量。

但是,我收到错误'local_variables' of '__b' is not defined。有没有什么办法解决这一问题?

感谢

+0

也许问题是没有'Binding#local_variables ='方法,只有reader [method](https://ruby-doc.org/core-2.3.0/Binding html的#方法-I-local_variables)。你可以使用'Binding#local_variable_set'来附加新值吗? – Aleksey

+0

@Aleksey我也想知道。我确实尝试过'__b.local_variable_set',但显然这个方法没有定义。然而,只是尝试'__b.eval(“本地人=#{当地人}”),似乎工作正常。然而,轻微的问题......'Kernel.local_variables'似乎返回变量的名称而不是变量的值... – Sancarn

+0

你可以通过'Binding#local_variable_get'或'eval'获得变量的值捆绑。 – Aleksey

回答

0

测试的一个位后,我想出了这个:

__b.eval("locals = #{locals}") 

不过......我意识到,这只是返回本地变量的名字,而不是值的变量...