从 Ruby 程序执行 Ruby 程序的最佳方式是什么?

发布于 2024-09-14 23:33:04 字数 336 浏览 4 评论 0原文

我想在循环内从 Ruby 脚本执行类似的操作:

  1. 写入文件 a.rb (每次迭代都会更改)
  2. 执行 system(ruby 'a.rb')
  3. a.rb 将带有结果的字符串写入文件'results'
  4. a.rb 完成,Ruby 返回 'true'(假设没有错误),
  5. 调用脚本读取文件 'results' 并采取操作。

我希望有很多更好的方法可以做到这一点。例如,我可以代替步骤 #2-#5 只需加载“a.rb”(在循环内)并调用其方法之一?使用 eval() 或其他方法有更好的方法吗? (了解元编程是我的 Ruby 待办事项列表。)

I would like to do something like this from a Ruby script, within a loop:

  1. Write a file a.rb (which changes each iteration)
  2. execute system(ruby 'a.rb')
  3. a.rb writes a string with results to a file 'results'
  4. a.rb finishes and Ruby returns 'true' (assuming no errors)
  5. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸢与 2024-09-21 23:33:04

我认为 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 creating a.rb at all, just eval('some-code-that-would-be-in-a.rb').

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文