From: "Y. NOBUOKA" Date: 2010-10-13T18:08:44+09:00 Subject: Re: sort_by: multiple fields with reverse sort The one way to do a reverse sort is wrapping a sort target in a class for a reverse sort. For instance: # This class is a class for a reverse sort. # An Object of various datatypes can be wrapped in an object of this class. class ItemForReverseSort def initialize( item ) @item = item end def item @item end def <=>( target ) ( self.item <=> target.item ) * (-1) end end b = [ ["radio", 30, 5], ["radio", 20, 5], ["archie", 20, 5], ["newton", 10, 3] ] # normal sort p b.sort_by{|x| [ x[1], x[0] ]} #=> [["newton", 10, 3], ["archie", 20, 5], ["radio", 20, 5], ["radio", 30, 5]] # normal sort for 1st item, and reverse sort for 2nd item p b.sort_by{|x| [ x[1], ItemForReverseSort.new(x[0]) ]} #=> [["newton", 10, 3], ["radio", 20, 5], ["archie", 20, 5], ["radio", 30, 5]] 2010/10/13 Rahul Kumar : > I need to use *sort_by* to sort a table, since the user could select > columns in any order. > >    b=[ ["radio", 30, 5], ["radio", 20, 5], ["archie", 20, 5], > ["newton", 10, 3] ] >    b.sort_by{|x| [ x[1], x[0] ]} > > Works fine. However, often the user will want a reverse sort on some > field. I do not off-hand know the datatype of the field, but in most > cases it will be a String. > > I tried: > >    b.sort_by{|x| [ !x[1] ]} > This works (one criteria), but this does not: >    b.sort_by{|x| [ !x[1], x[0] ]} > > Another thread here, suggested using a minus for Numbers but what about > Strings. > Thx, rahul. -- NOBUOKA Yuya