From: Ralph Mason Date: 2001-11-30T14:37:35+09:00 Subject: [ruby-talk:27027] Re: Help: factored sorting It's just a matter of making the all the items count so your expression should be something like def val(x) x[0] * 1000 + x.scan(/\d+/).to_s.to_i end a.sort { |a,b| sval(a) <=> sval(b) } As someone once said, I have not tried this but it should work Ralph ----- Original Message ----- From: "Bil Kleb" Newsgroups: comp.lang.ruby To: "ruby-talk ML" ; Sent: Friday, November 30, 2001 6:16 PM 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 >