On Sat, 19 Jul 2003 18:41:33 +0900, Brian Candler wrote:

> 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 :-)

Work smarter, Not harder.
I know sort, But this solution didn't come to mind.


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

Yes. Avoiding temporary copy were my goal when I started writing it.
As you can see I apparently forgot it in the hurry :-) 
 

[snip enum#ordered?]
> 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 :-)

Enum is Nice.

Some more thoughts on #ordered?

Supplying an operator, could be useful? 

[3, 2, 1].ordered? :>    #=> true
[2, 2, 2].ordered? :>    #=> false
[2, 2, 2].ordered? :>=   #=> true


Supplying an block could also be useful?

[2, 2, 2].ordered? { |a, b|  (((a-b) ^ (b-a)) % 3) == 0 }
#=> true

[1, 2, 3].ordered? { |a, b|  (((a-b) ^ (b-a)) % 3) == 0 }
#=> false

--
Simon Strandgaard