質問

I am reading Matz's book "Programming Ruby", and in chapter 9, in the part about Threads, I read this code:

module Enumerable
  def concurrently
    map{|item| Thread.new{ yield item }}.each{|t| t.join}
  end
end

I know the map method is used for actions with arrays or collections, and in this example it shows it without self or some object.

I'm confused how map works in this example.

役に立ちましたか?

解決 2

Here map is defined on any class which mixes in Enumerable.

It will be called on self from any Enumerable object, when you call object.concurrently { |x| # whatever } and the use of it is that it will spawn a large number of threads to evaluate the blocks.

Further, using map in the pattern from the book, means that you get the same behaviour as Enumerable#map with whatever additional effect is used before, around and after the yield. In this case, that is starting each block evaluation in its own thread.

他のヒント

Calling a method without an explicit receiver calls the method on self so even though "it shows without self" the self is implicitly present as the default receiver. That method is more or less the same as:

def concurrently
  self.map{|item| Thread.new{ yield item }}.each{|t| t.join}
 #^^^^^ This is implicit.
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top