From: Paul Date: 2010-10-06T06:10:19+09:00 Subject: Re: Sorting problem with an Array of Arrays Hi Jeremy, I tried this code but I get an error on the line idx = arr.index { |item| new_item[1] < item[1] } :in `index': wrong number of arguments (0 for 1) (ArgumentError) Can you tell me how I can get your code below to work? You also mentioned working with classes (in a previous reply) as an alternate way of organizing this data. Do you know where I can find examples or docs to help me learn how to do this? I still don't have an algorithm that finds all the problems that I can catch by eye. It's just hard to catch them all when looking at lists of 1000's of records. TIA On Sep 23, 4:46 pm, Jeremy Bopp wrote: > What you appear to be describing is actually an ordered insert operation > rather than a strict sort operation.  Array#sort is abstracted such that > you cannot know at any given time what is already sorted in yourarray, > so you cannot conditionally change your primary sort key from label to > timestamp based upon what is currently the last entry of the sortedarray. > > You need to define a custom insert function.  Beware that your > description of labels and how they "change" is ambiguous, so you may > need to modify the label comparison logic in the function to capture > what it really means to have different labels: > > def special_insert(arr, new_item) >   if arr.empty? || new_item[0] == arr.last[0] then >     # If thearrayis empty or the label of the new item is the same >     # as the label of the last item in thearray, append the new item >     # to thearray. >     arr << new_item >   else >     # Otherwise, insert the new item by its timestamp. >     idx = arr.index { |item| new_item[1] < item[1] } >     if idx.nil? then >       # The new item is the oldest, so append it. >       arr << new_item >     else >       # Otherwise, insert the new item before the first item younger >       # than it is. >       arr.insert(idx, new_item) >     end >   end > end > > unsorted_arr = [ >   ["AAA-1", 1271862000, 2], >   ["ABC-1", 1271768400, 2], >   ["ABC-2", 1271773800, 1], >   ["ABC-3", 1271863200, 2], >   ["ABC-4", 1271869200, 2], >   ["DEF-1", 1271772000, 1] > ] > > sorted_arr = [] > > unsorted_arr.each do |item| >   special_insert(sorted_arr, item) > end > > puts sorted_arr.collect { |item| "[#{item.join(", ")}]" }.join("\n")