Alex Young
3/27/2007 4:17:00 PM
Rick DeNatale wrote:
> On 3/26/07, Alex Young <alex@blackkettle.org> wrote:
<snip>
>> 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