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.
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.