[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: stable sort_by?

Kroeger, Simon (ext)

12/13/2005 3:37:00 PM


I guess you have to use sort instead of sort_by in such a case,
like:

test = [[1, 'b'], [1, 'c'], [1, 'a'], [0, 'a']]

#sort for first item, than for second in reverse order
p test.sort{|a, b|(a[0] <=> b[0]).nonzero? || (b[1] <=> a[1]) }

=>[[0, "a"], [1, "c"], [1, "b"], [1, "a"]]

cheers

Simon

> -----Original Message-----
> From: list-bounce@example.com
> [mailto:list-bounce@example.com] On Behalf Of Mike Fletcher
> Sent: Tuesday, December 13, 2005 3:57 PM
> To: ruby-talk ML
> Subject: Re: stable sort_by?
>
> Frederick Ros wrote:
> > h.sort_by {|k,v| [v[:a],v[:b],v[:c],v[:d]]}.reverse
>
> OK, this or something like it should be in the rdoc for
> sort_by. I was
> doing something similar and wound up writing a similar sort with
> multiple if tests like the OP because I didn't remember that Array
> implements a sane <=>.
>
> Also, would there be a similar cool way to do this in one
> step where you
> want a mix of ascending and descending sorts on different
> parts? Say I
> had a hash (in YAML):
>
> Bobby:
> age: 11
> lastname: Smith
> Suzy:
> age: 13
> lastname: Jones
> Ted:
> age 12
> lastname: Smith
>
> And I wanted to sort
> - alphabetically by lastname
> - then age oldest to youngest
>
> So in Perl I'd do something like:
>
> my @sorted_keys = sort { $a->{lastname} cmp $b->{lastname}
> || $b->{age} <=> $a->{age} }
> keys %data;
>
> In this case I could use
>
> sorted_keys = data.sort_by { |k,v| [ v["lastname"], -1*v["age"] ] }
>
> But what if I wanted reverse alphabetically by lastname
> (Z-A)? In perl
> I'd swap $a and $b in the first comparison, but I can't think of a
> spiffy way to do the same using sort_by.
>
> --
> Posted via http://www.ruby-....
>
>


1 Answer

Mike Fletcher

12/13/2005 4:25:00 PM

0

Kroeger, Simon (ext) wrote:
> I guess you have to use sort instead of sort_by in such a case,
> like:
>
> test = [[1, 'b'], [1, 'c'], [1, 'a'], [0, 'a']]
>
> #sort for first item, than for second in reverse order
> p test.sort{|a, b|(a[0] <=> b[0]).nonzero? || (b[1] <=> a[1]) }
>
> =>[[0, "a"], [1, "c"], [1, "b"], [1, "a"]]
>

Aaah, it's chaining with nonzero? (since it'll return the -1 or 1 if
that's the case) that I was missing.

Thanks.

--
Posted via http://www.ruby-....