如何调用多个过程?
给定以下代码,我可以在这方面使用一些帮助:
result1, result2, result3 = do_stuff {
method_1
method_2
method_3
}
我希望能够编写一个名为 do_stuff 的方法,该方法可以单独调用该块的每一行并返回每行/块的结果。能做到吗?我是否以错误的方式处理这个问题?我正在想这样的事情(根本不起作用)。
def do_stuff(&block)
block.each_block do |block|
block.call
end
end
编辑:我想要完成的是能够并行运行方法“do_stuff”内的每个方法/块调用(在它自己的线程中),并在每个方法调用周围添加一些日志记录。
I could use some help on this one, given this code:
result1, result2, result3 = do_stuff {
method_1
method_2
method_3
}
I would like to be able to write a method called do_stuff that can call each line of that block individually and return a result for each line/block. Can it be done? Am I going about this the wrong way? Something like this (doesn't work at all) is what I am thinking.
def do_stuff(&block)
block.each_block do |block|
block.call
end
end
EDIT: What I am trying to accomplish is to be able to run each method/block call inside the method "do_stuff" in parallel (in it's own thread) and also add some logging around each method call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意上面的 mu ,你应该解释你想要做什么,因为可能有更合适的模式可以使用。
顺便说一句,你可以做你所要求的一个小的改变:
或者,也许,更优雅,没有块:
:)
I agree with mu above, you should explain what you are trying to do, as there is probably a more suitable pattern to use.
BTW, you can do what you ask for with a minor change:
or, perhaps, more elegantly, without the block:
:)
好的,问题更新后看起来更清楚了。您可以使用
method_missing
、instance_eval
和线程执行类似的操作:不过请注意,这还没有经过充分测试,而且我不确定线程安全性如何。
OK, it looks clearer after the question was updated. You could do something like this, using
method_missing
,instance_eval
and threads:Be careful, though, that this is not well-tested and I am not sure how threadsafe.