From: raja@... (Raja S.) Date: 2001-11-30T15:36:24+09:00 Subject: [ruby-talk:27034] Re: Help: factored sorting Bil Kleb writes: >I have an array of strings, >a = ["d3", "d33", "d4", "r16", "r33", "d34", "r34"] >which I'd like to sort by both the numerical suffix and by >the alphabetic prefix, i.e., I'd like the result, > ["d3", "d4", "d33", "d34", "r16", "r33", "r34"] >or, even better would be an array of two prefix-keyed >sub arrays that I could exploit with the assoc method, >viz, > [ ["d", "d3", "d4", "d33", "d34"], ["r", "r16", "r33", "r34"] ] Hmmm ... thinking about the later part, seems easier to split it into two: 1. the sorting described in an earlier note followed by 2. a "gathering" phase: def gather( sorted_ary ) hsh = {} sorted_ary.each do |x| primary_key = keys(x).first if hsh.has_key?(primary_key) hsh[primary_key] << x else hsh[primary_key] = [primary_key, x] end end result = [] hsh.keys.sort.each do |key| result << hsh[key] end result end gather( a.sort{ |x,y| keys(x) <=> keys(y) } ) regards, Raja