From: "(r.*n){2}" Date: 2010-09-23T12:10:13+09:00 Subject: Re: Sorting problem with an Array of Arrays On Sep 22, 6:54 pm, Jeremy Bopp wrote: > On 9/22/2010 5:43 PM, Jeremy Bopp wrote: > > > > > > > On 9/22/2010 5:35 PM, Paul wrote: > >> Hi there, I have an array of arrays that looks like the following: > > >> arr1 = [["ABC-1", 1271768400, 2],  ["ABC-2", 1271773800, 1], > >>  ["ABC-3", 1271863200, 2],  ["ABC-4", 1271869200, 2], > >>  ["AAA-1", 1271862000, 2],  ["DEF-1", 1271772000, 1]] > > >> Desired sort order: > >> (1) label (1st element = all unique) > >> (2) different labels (e.g. AAA, DEF) need to be inserted according to > >> timestamp (2nd element), but maintain (1) label sort order; so AAA-2 > >> can't come before AAA-1. (I don't have that data point here but it > >> happens) > > >> => I don't know how to do (2), so I just have the AoA sorted by (1) > >> right now. > > >> Is there a way to do this?  I'm trying to find duplicate and > >> overlapping timestamps but my current method for checking this is > >> getting complicated, so I thought I'd check to see if there's a good > >> way to sort the data properly in the first place. > > > You could define a class to represent each of your inner array elements. > >  That class could then define the <=> method in which you could compare > > each item in the order you desire.  Then your outer array, consisting of > > instances of your class, could be trivially sorted with Array#sort. > > Silly me.  You can also pass a block to the Array#sort method.  That > block will receive 2 arguments which you may then compare as you wish, > returning -1 if the first argument sorts before the last, 0 if they are > equal, and 1 if the last argument sorts before the first. > > -Jeremy arr2 = arr1.sort { |x,y| (x[0] <=> y[0]) * 10 + (x[1] <=> y[1]) } or arr1.sort! { |x,y| (x[0] <=> y[0]) * 10 + (x[1] <=> y[1]) }