Reputation: 270
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.
Upvotes: 1
Views: 93
Reputation: 27207
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.
Upvotes: 2
Reputation: 434665
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
Upvotes: 5