Method to sort strings in descending order (in complex keys)

Viewed 457

In order to descend-sort an array a of strings, reverse can be used.

a.sort.reverse

But when you want to use a string among multiple sort keys, that cannot be done. Suppose items is an array of items that have attributes attr1 (String), attr2 (String), attr3 (Integer). Sort can be done like:

items.sort_by{|item| [item.attr1, item.attr2, item.attr3]}

Switching from ascending to descending can be done independently for Integer by multiplying it with -1:

items.sort_by{|item| [item.attr1, item.attr2, -item.attr3]}

But such method is not straightforward for String. Can such method be defined? When you want to do descending sort with respect to attr2, it should be written like:

items.sort_by{|item| [item.attr1, item.attr2.some_method, item.attr3]}
4 Answers
Related