1

鉴于此代码,我可以对此使用一些帮助:

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”中并行运行每个方法/块调用(在它自己的线程中),并在每个方法调用周围添加一些日志记录。

4

2 回答 2

1

好的,问题更新后看起来更清楚了。你可以做这样的事情,使用method_missinginstance_eval线程:

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

不过要小心,这没有经过充分测试,我不确定线程​​安全性如何。

于 2011-08-16T07:45:44.890 回答
1

我同意上面的 mu,您应该解释您要做什么,因为可能有更合适的模式可以使用。

顺便说一句,你可以做你所要求的一个小的改变:

result1, result2 = do_stuff {
  [
    method_1,
    method_2,
    method_3
  ]
}

或者,也许,更优雅,没有块:

result1, result2 = [
  method_1,
  method_2,
  method_3
]

:)

于 2011-08-15T06:04:19.757 回答