From: Alex Young Date: 2007-03-28T01:16:56+09:00 Subject: Re: sorting an array based on two attributes of objects Rick DeNatale wrote: > On 3/26/07, Alex Young wrote: >> In this case, just invert the salary: >> >> sorted_employees = employees.sort_by { |e| [ -e.salary, e.name ] } >> >> I can't think of a way offhand to have different lexicographic orderings >> in the same sort, though. > > Someone, in another recent thread, came up with the idea of a reverse > proxy class something like this > > class Reverse > > :attr_reader :obj > > def initialize(obj) > @obj = obj > end > > def <=>(other) > other.obj <=> self.obj > end > > end > > so let's say you wanted to sort the names in descending order as well: > sorted_employees = employees.sort_by { |e| [-e.salary, > Reverse.new(e.name) ] } > > You could even use this "reverse" proxy to change the sorting of > salary, so that the original could be: > > sorted_employees = employees.sort_by { |e| [ Reverse.new(e.salary), > e.name ] } That's lovely. My brain wandered off down the String#invert route, and I ended up getting tied in knots over multibyte encodings. Reverse is a *much* nicer trick. -- Alex