Apparently the other post got overlooked - and it had an error in the
implementation.  What do others think of this suggestion of a changed
Enumerable#inject that uses a sliding window whose size is determined by
the block's arity.

With this implementation you can do the usual injection tricks plus
everything that needs more than one argument:

# ordered?
enum.inject(true) {|c,a,b|c&&a<b}

# differentiation
enum.inject([]) {|m,x,y|m<<(y-x).to_f/2}

# integration
enum.inject([]) {|m,x,y|m<<(x+y).to_f/2}

# weighted integration
enum.inject([]) {|m,x,y,z|m<<(x+y+y+z).to_f/4}

What do you think?  Is this a reasonable replacement for inject or an
additional method?

Cheers

    robert


module Enumerable
  def inject(val=nil, &bl)
    raise "Block missing" unless bl

    size = bl.arity
    raise "Need block with at least 1 argument" if size == 0

    size = size < 0 ? 1+size : size-1

    if size == 0
      # 1 arg
      each do |e|
        val = yield val
      end
    else
      # >1 args
      args=[]

      each do |e|
        args.push e

        if args.length == size
          val = yield val, *args
          args.shift
        end
      end
    end

    val
  end
end