【问题标题】:Append Kernel.local_variables to scope of binding将 Kernel.local_variables 附加到绑定范围
【发布时间】:2017-09-24 23:13:40
【问题描述】:

我为一个能够运行 ruby​​ 脚本的软件制作了一个基本的 REPL。我希望能够在启动时将变量从前一个作用域传递到 REPL,这样我就可以轻松调试我的代码。

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。有没有办法解决这个问题?

谢谢

【问题讨论】:

  • 可能问题是没有Binding#local_variables=方法,只有读者method。您可以使用Binding#local_variable_set 附加新值吗?
  • @Aleksey 我也想知道。我确实尝试过__b.local_variable_set,但显然该方法未定义。但是刚刚尝试了__b.eval("locals = #{locals}"),这似乎工作正常。但是,小问题...Kernel.local_variables 似乎返回变量的名称而不是变量的值...
  • 你可以通过Binding#local_variable_get或者eval绑定来获取变量的值。
  • 但是在这种情况下有什么约束力?喜欢这个launchREPL(Binding#local_variable_get)
  • Binding 我的意思是 Ruby 类,你可以调用 Kernel#binding 方法的实例。

标签: ruby scope read-eval-print-loop


【解决方案1】:

后来进行了一些测试,我想出了这个:

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

但是...我意识到这只是返回局部变量的名称而不是变量的值...

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 2017-07-15
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多