"reversing" a Time

Hello,

is it possible to reverse order when using a Time as sort key for
sort_by?

I know I could use sort, and time2 <=> time1, but it’s getting
complicated when the sort key is compound, like

sort_by{|e| [e.name, e.time]}

With e.g. numerics I can simply negate the value for reverse order, but
I can’t negate a Time (or a String, for that matter).

thx
mortee

mortee wrote:

Hello,

is it possible to reverse order when using a Time as sort key for
sort_by?

I know I could use sort, and time2 <=> time1, but it’s getting
complicated when the sort key is compound, like

sort_by{|e| [e.name, e.time]}

With e.g. numerics I can simply negate the value for reverse order, but
I can’t negate a Time (or a String, for that matter).

if the time is just the UNIX time can’t you negate it too? can use
to_f first.

and then to negate a string probably is too expensive… using 255 to
subtract its ASCII value or XOR each character with 0xFF.

how about just use sort {|x, y| [y.name, x.time] <=> [x.name, y.time] }
so now the name is “negated”.

Couldn’t you just do

sort_by{|e| [e.name, e.time]}.reverse

?

is it possible to reverse order when using a Time as sort key
for sort_by?

I know I could use sort, and time2 <=> time1, but it’s getting
complicated when the sort key is compound, like

sort_by{|e| [e.name, e.time]}

For your special case of using time as a sort key, just convert the time
to an integer

sort_by {|e| [e.name, -e.time.to_i] }

Dan.

SpringFlowers AutumnMoon wrote:

if the time is just the UNIX time can’t you negate it too? can use
to_f first.

Daniel S. wrote:

For your special case of using time as a sort key, just convert the time
to an integer

Yeah, this is what I was looking for.

how about just use sort {|x, y| [y.name, x.time] <=> [x.name, y.time] }
so now the name is “negated”.

… and this is right what I wanted to avoid.

mortee

Sascha A. wrote:

Couldn’t you just do

sort_by{|e| [e.name, e.time]}.reverse

?

No, because I just wanted to reverse the order of one component, not the
entire sequence.

mortee

On Sun, 14 Oct 2007 21:27:53 +0900, mortee wrote:

With e.g. numerics I can simply negate the value for reverse order, but
I can’t negate a Time (or a String, for that matter).

thx
mortee

The integer solutions others have given are more elegant, but just for
completeness…

I believe sort_by implements a stable sort, meaning it doesn’t change
the
order of equivalent elements, so you could sort

sort_by{|e| e.time}.reverse.sort_by{|e| e.name}

–Ken