On Sat, Jul 19, 2003 at 05:08:03PM +0900, Simon Strandgaard wrote:
> You can do this:
> 
> if [1, 2, 3].ordered?
>     puts "ok"
> end
> 
> 
> It will require that you extend the Array class yourself, like this:
> 
> > expand -t4 b.rb
> class Array
>     def ordered?
        self == sort
      end
  end

(I'm a lazy typist :-)

Both versions generate a temporary copy of the array, e.g. self[1..-1] does
that too. But you can avoid it:

module Enumerable
  def ordered?
    first = true
    prev = nil
    each do |item|
      if first
        first = false
      else
        return false if prev > item
      end
      prev = item
    end
    return true
  end
end

You can then check whether all the lines in a file are ordered, for example,
without reading it into memory. (I am a big fan of Enumerable :-)

Regards,

Brian.