module Parallel def cpu_cores 2 end def parallel_each(&block) t = [] each_slice(cpu_cores).each do |items| t << Thread.new do items.each do |item| yield item end end end t.collect(&:join) end def parallel_sum t = [] each_slice(cpu_cores).each do |items| puts "Thread.." t << Thread.new do Thread.current[:output] = items.inject(&:+) end end output = 0 t.each do |thread| thread.join output += thread[:output] end output end end class Array prepend Parallel end Array.new([1,2,3,4,5]).parallel_each do |a| puts "#{a}" sleep (1..5).to_a.sample end puts Array.new([1,2,3,4,5]).parallel_sum