Extend Ruby Enumerables With An EachN Processor

Here’s a useful enhancement to arrays that allows you to process elements in a block n at a time. N is inferred by the arity of your block signature.

require 'enumerator'

module Enumerable
  def eachn(&block)
    n = block.arity
    each_slice(n) {|i| block.call(*i)}
  end
end

a = (1..10).to_a
a.eachn {|x,y,z| p [x,y,z]}

Namaste…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s