如何每次都在新的上下文中评估 JRuby 中的代码?
我想允许在类似 shell 的应用程序中评估代码。按一下按钮,代码就会被评估并向用户显示结果。我想这样做,以便如果他再次评估代码,旧评估中定义的所有内容都将不再存在。例如,假设这是 eval #1:
puts "Hello world"
user_variable1 = 10
$USER_VARIABLE2 = 20
我希望在 eval #2 上,user_variable1
和 $USER_VARIABLE2
的值不存在。这就是为什么我考虑在每次运行时使用某种上下文。但是,我不知道在哪里可以找到更多信息。
I want to allow evaluation of code in a shell-like app. At a press of a button, the code will be evaluated and a result will be showed to the user. I want to make it so that if he evaluates code again, everything defined in old evaluation will no longer exist. For example, imagine this is eval #1:
puts "Hello world"
user_variable1 = 10
$USER_VARIABLE2 = 20
I want that on eval #2, the values of user_variable1
and $USER_VARIABLE2
not to exist. This is why I'm thinking of using some kind of context on each run. However, I don't know where to look for more info.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用某种执行命令的方式在另一个进程中运行另一个(或相同的脚本)。类似
or
这样将确保清除所有变量,但是环境变量当然是相同的。不过,从 ruby 1.9 开始你也可以重置它们。像这样:
如果您想要非常接近
eval()
函数的东西,您可以创建一个eval.rb
,它只会评估第一个参数,然后定义一个 < code>evalExt 函数:eval.rb:
然后在您的其他脚本中:
def evalExt(脚本)
system("eval.rb \"#{script}\"", :unsetenv_others => true)
如果是JRuby
,您应该能够轻松调用另一个 ruby 引擎,方法是从 JRuby 调用 Java 代码,然后使用
ScriptEngineManager
,如 Wikipedia:也许您必须确保重置脚本上下文或绑定(请参阅本文)。
话虽如此,也许最简单的解决方案就是确保没有设置全局变量,那么您根本不必分离上下文。
You could just run another (or the same script) in another process using some way of executing the commands. Something like
or
This will ensure that any variables are cleared, however, the environment variables will of course be the same. Since ruby 1.9 you can reset them too, though. Like so:
If you want something very close to the
eval()
function, you could create aneval.rb
, that will just evaluate the first parameter and then define anevalExt
function:eval.rb:
And then in your other script:
def evalExt(script)
system("eval.rb \"#{script}\"", :unsetenv_others => true)
end
In case of JRuby you should be able to invoke another ruby engine as easily, by calling Java code from JRuby and then using the
ScriptEngineManager
as described on Wikipedia:Maybe you will have to ensure to reset the script context or bindings (see this article).
All that said, maybe the easiest solution would be to just ensure that no global variables are set, then you do not have to seperate contexts at all.