Module: Enumerable
- Defined in:
- lib/forkify.rb
Instance Method Summary collapse
-
#forkify(opts = {}, &block) ⇒ Object
Forkify will process block’s actions using processes.
Instance Method Details
#forkify(opts = {}, &block) ⇒ Object
Forkify will process block’s actions using processes. If no number of processes is given, the default of 5 will be used. If there are less than procs number of items in the Enumerable
type, less processes will be spawned.
It should be noted that forkify will always return an Array
at this time, so be careful with Hash
objects.
Examples
[1, 2, 3].forkify { |n| n*2 } => [2, 4, 6]
{:a => 1, :b => 2, :c => 3}.forkify { |k, v| [v, k] } => [[1, :a], [2, :b], [3, :c]]
10.times.forkify(10) { sleep(1) } => [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] (runs for less than 2 seconds)
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/forkify.rb', line 25 def forkify(opts = {}, &block) puts opts.inspect if FORKIFY_DEBUG if opts.class == Fixnum # it's the number of processes procs = opts method = :serial elsif opts.class == Hash procs = opts[:procs] || 5 method = opts[:method] || :serial end puts "procs: #{procs}, method: #{method.inspect}" if FORKIFY_DEBUG if method == :serial forkify_serial(procs, &block) elsif method == :pool if RUBY_VERSION < "1.9.1" raise "Pool forking is only supported on Ruby 1.9.1+" end forkify_pool(procs, &block) else raise "I don't know that method of forking: #{method}" end end |