从 Ruby 生成 Ruby 程序
假设我有一个名为 hello_world.rb 的 ruby 脚本,其中有一行
puts "Hello, world"
,我想从另一个名为 spawn_hello_world.rb 的 ruby 脚本调用该
pipe = IO.popen("ruby1.9.1 hello_world.rb", 'w+')
if pipe
puts pipe.gets
end
脚本 我的问题是:是否有一种快捷方式可以运行另一个 ruby 进程,而无需在此调用操作系统方式?
我知道我可以这样做
pipe = IO.popen('-', 'w+')
,这将启动另一个红宝石解释器,然后我可以使用它发送命令
pipe.puts "puts "Hello World""
但这似乎也很不优雅。
我基本上正在寻找一个与 python 的 多处理模块 等效的 ruby
Say I have a ruby script called hello_world.rb that has one line
puts "Hello, world"
And I want to call that from another ruby script called spawn_hello_world.rb
pipe = IO.popen("ruby1.9.1 hello_world.rb", 'w+')
if pipe
puts pipe.gets
end
My question is: Is there a shorthand way of running another ruby process without having to call the OS in this way?
I'm aware I could do
pipe = IO.popen('-', 'w+')
which would start another ruby interpreter and I could then send it commands using
pipe.puts "puts "Hello World""
But this seems quite inelegant as well.
I'm basically looking for a ruby equivalent to python's multiprocessing module
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在代码自身绑定的上下文中使用
eval
。这将允许您执行任意代码,同时仍然封装您的程序,使其免受该代码的讨厌的副作用。它并不完全运行另一个 Ruby 解释器,但它会为您执行您的 Ruby 代码。
You could use
eval
on the code in the context of it's own binding. This would allow you to execute arbitrary code while still encapsulating your program from the nasty side effects of that code.It's not quite running another Ruby interpreter, but it will execute your ruby code for you.
您能给我们一些背景信息吗?你打算做什么?难道您不能重构代码以使用 "require" 或“包含”方法?
只是好奇。
路易斯
Could you please give us some context here? What do you intend to do? Can't you just refactor your code to use the "require" or "include" methods?
Just curious.
Luis