2017-04-27 48 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}") 

不過......我意識到,這只是返回本地變量的名字,而不是值的變量...