How do I call multiple procs?
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.cal开发者_如何学Cl
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.
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:
result1, result2 = do_stuff {
[
method_1,
method_2,
method_3
]
}
or, perhaps, more elegantly, without the block:
result1, result2 = [
method_1,
method_2,
method_3
]
:)
OK, it looks clearer after the question was updated. You could do something like this, using method_missing
, instance_eval
and threads:
class Parallelizer
class << self
def run(receiver, &block)
@receiver = receiver
instance_eval &block
# wait for all threads to finish
@threads.each{|t| t.join}
@results
end
def method_missing *args, &block
@threads ||= []
@results ||= []
@threads.push Thread.new{
# you could add here custom wrappings
@results.push(@receiver.send(*args, &block))
}
end
end
end
class Test
def take_a_break name, sec
puts "#{name} taking a break for #{sec} seconds"
Kernel.sleep sec
puts "#{name} done."
name
end
end
t = Test.new
results = Parallelizer.run(t) do
take_a_break 'foo', 3
take_a_break 'bar', 2
take_a_break 'baz', 1
end
Be careful, though, that this is not well-tested and I am not sure how threadsafe.
精彩评论