From: Mike Fletcher Date: 2005-12-13T23:56:38+09:00 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-forum.com/.