【发布时间】: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