On 20 Jul 2003 at 0:10, Brian Candler wrote:

> Which implementation of 'inject' are you using? The one in PragProg requires
> an initial value to be passed as a parameter.

It's Andy's Windows installer version:

D:\Temp>ruby -v
ruby 1.8.0 (2003-05-26) [i386-mswin32]


And ri says about inject:

D:\Temp>ri inject
This is a test 'ri'. Please report errors and omissions
on http://www.rubygarden.org/ruby?RIOnePointEight

------------------------------------------------------ 
Enumerable#inject
     enumObj.inject(initial) {| memo, obj | block } -> anObject
     enumObj.inject {| memo, obj | block }  -> anObject
---------------------------------------------------------------------
  Combines the elements of enumObj by applying the block to an
  accumulator value (memo) and each element in turn. At each step,
  memo is set to the value returned by the block. The first form lets
  you supply an initial value for memo. The second form uses the
  first element of the collection as a the initial value (and skips
  that element while iterating).

> With an array of N elements you either need to do N-1 comparisons,

This is what the second form does.

> or you
> need to start with a sentinel value which is guaranteed to be less than all
> other elements (nil and 0 both aren't suitable).

This is what the first form would do.

BTW, if you wanted to add the compare method as a parameter as 
someone else suggested, you could define

module Enumerable
  def ordered?( compare_method = :< )
    inject { | last, item |
      return false unless last.send( compare_method, item )
      item
    }
    true
  end
end

and then call it like

p [ 1, 2, 2 ].ordered?         #  => false
p [ 1, 2, 2 ].ordered?( :<= )  #  => true

Isn't it fun to code in Ruby :< )

Regards,
Pit