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 comment