从 Ruby 程序执行 Ruby 程序的最佳方式是什么?
我想在循环内从 Ruby 脚本执行类似的操作:
- 写入文件 a.rb (每次迭代都会更改)
- 执行 system(ruby 'a.rb')
- a.rb 将带有结果的字符串写入文件'results'
- a.rb 完成,Ruby 返回 'true'(假设没有错误),
- 调用脚本读取文件 'results' 并采取操作。
我希望有很多更好的方法可以做到这一点。例如,我可以代替步骤 #2-#5 只需加载“a.rb”(在循环内)并调用其方法之一?使用 eval() 或其他方法有更好的方法吗? (了解元编程是我的 Ruby 待办事项列表。)
I would like to do something like this from a Ruby script, within a loop:
- Write a file a.rb (which changes each iteration)
- execute system(ruby 'a.rb')
- a.rb writes a string with results to a file 'results'
- a.rb finishes and Ruby returns 'true' (assuming no errors)
- the calling script reads the file 'results' and takes action.
I expect there are many better ways of doing this. For example, instead of step #2-#5 could I
simply load 'a.rb' (within the loop) and invoke one one of its methods? Is there a better way by using eval() or something else? (Gaining an understanding of metaprogramming is on my Ruby to-do list.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 eval 可能是动态生成代码的正确解决方案;这就是它的设计目的。根本不需要创建
a.rb
,只需eval('some-code-that-would-be-in-a.rb')
即可。I think
eval
is probably the right solution for dynamically-generated code; that's what it's designed for. Instead of creatinga.rb
at all, justeval('some-code-that-would-be-in-a.rb')
.