Forkify 0.0.1 Ruby gem released, threadify with processes

I’m happy to announce the release of another tiny Ruby gem, Forkify.

Forkify is basically Ara Howard’s Threadify (minus a few features), but instead of using threads, it uses fork to create multiple processes to perform the operations on an Enumerable type. It was born out of the desire to have the forkoff gem work on Ruby 1.9.1 (which it isn’t currently).

You can get Forkify using RubyGems:

sudo gem install forkify

Using it is super-simple also:

require 'forkify'
require 'pp' # optional, just for this example
r = [1, 2, 3].forkify { |n| n*2 }
pp r

=> [2, 4, 6]

Another example demonstrating the time-saving feature of using forks:

[3:hinmanm@Xanadu:~]% time ruby -rforkify -e “5.times.forkify { |n| sleep(1) }”
ruby -rforkify -e “5.times.forkify { |n| sleep(1) }”  0.02s user 0.03s system 5% cpu 1.030 total

[3:hinmanm@Xanadu:~]% time ruby -r forkify -e "5.times.forkify { |n| sleep(1) }"
ruby -r forkify -e "5.times.forkify { |n| sleep(1) }"  0.02s user 0.03s system 5% cpu 1.030 total

You can specify the maximum number of processes to spawn with an argument to forkify, the default is 5:

[1, 2, 3, 4, 5, 6].forkify(3) { |n| n**2 } # This will spawn 3 processes at a time to process the 6 items

Here you can see sleeping for 5 seconds 5 times only takes slightly longer than 1 second (instead of over 5 if you hadn’t forkified it)

Forkify is available as a gem via rubygems, or you can check out the code here: http://github.com/dakrone/forkify/. It’s still beta-quality, so please let me know if you run into any issues with it.

P.S. 100th post, woo!

Nesting traps in Ruby with a quick monkeypatch

If you end up messing with traps a lot in Ruby, you’ll find that they don’t unbind when leaving function context, so you’re either stuck ‘ensuring’ that the trap is replaced by the old trap, or just dealing with it.

Well, here’s a quick monkeypatch for adding a method that will do all the ensuring/retrapping for you when you leave a function.

Here’s the code (click for github’s colorized version):

While the syntax for calling it (t.trapr_wrap "SIGINT", Proc.new { ... }, :foo) isn’t exactly clean, if you’re calling a lot of functions and only want a trap to be active inside, it beats having to repeat undoing your trap every time.

Update: I changed the code for better readability and because I was doing it a silly way. Now it takes actual arguments instead of just ‘*args’.

Bad Behavior has blocked 250 access attempts in the last 7 days.