From: Bil Kleb Date: 2001-11-30T14:16:18+09:00 Subject: [ruby-talk:27026] Help: factored sorting 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"] ] A straight lexiconic sort, e.g., a.sort, gives all the d's followed by the r's, but does not yield the desired numerical ordering because the single and double digit integer suffixes, viz, ["d3", "d33", "d34", "d4", "r16", "r33", "r34"] Meanwhile an (inept?) numerical sorting, e.g., a.sort { |a,b| a.scan(/\d+/).to_s.to_i <=> b.scan(/\d+/).to_s.to_i } gives the desired numerical sequence, but mixes the d and r prefixes together, viz, ["d3", "d4", "r16", "d33", "r33", "d34", "r34"] Is there an elegant way to accomplish this type of factored sort without resorting to padding the digit suffix or similar convoluted mechanics? TIA, -- Bil