From: Tobias Reif Date: 2001-12-01T03:35:56+09:00 Subject: [ruby-talk:27104] Re: Help: factored sorting Bil Kleb wrote: > 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 sorry, there was trash included... ----- main_array = ["zed66","alfred39","x1","x3","x2","f5","f2","g7","g9"] # sort by first letter main_array.sort! # group by first letter group_array = [[]] current_group_index = 0 main_array.each_with_index do |element,index| if index == 0 group_array[0].push element elsif element[0].chr == main_array[index-1][0].chr group_array[current_group_index].push element else group_array.push [element] current_group_index += 1 end end # sort each group by number result = group_array.map do |group| group.sort do |a,b| a.scan(/\d+/).to_s.to_i <=> b.scan(/\d+/).to_s.to_i end end p result # -> [["alfred39"], ["f2", "f5"], ["g7", "g9"], ["x1", "x2", "x3"], ["zed66"]] ----- Tobi -- Tobias Reif http://www.pinkjuice.com/myDigitalProfile.xhtml go_to('www.ruby-lang.org').get(ruby).play.create.have_fun http://www.pinkjuice.com/ruby/