From: Wayne Brissette Date: 2012-03-27T19:26:53+09:00 Subject: Re: sort array of strings with integers On Mar 27, 2012, at 4:04 AM, Jan E. wrote: > > Strings are ordered lexicographically by default. That is, the > characters are compared one by one. This makes the string "a10" smaller > than "a2", because the character "1" is smaller than "2" (the rest of > the string is ignored). > > If you want to change this behavious, you have to provide your own > sorting rule: I found for some types of large sorts, I have better luck breaking things up, It also gives me the flexibility to do multiple types of sorts on the same data (I have one script for sorting chip ball maps where we need to do alpha sorts and then pin number sorts, so I use a routine similar to this: class Map < Struct.new(:char_alpha, :char_numb) end b = %w[a1 a3 a2 a4 a7 a6 a5 a8 a9 a10] storage = Array.new b.each do |item| a_char = Map.new item_alpha = item.split(/\d/) a_char.char_alpha = item_alpha item_number = item.split(/\D/) a_char.char_numb = item_number[1].to_i # convert to integer for sort storage.push(a_char) end b.clear # remove contents of old array storage.sort_by! { |a| [a.char_alpha, a.char_numb]} # sorting order performed here first by alpha then numeric storage.each do |f| # build new array for b sorted correctly tmp_item = f.char_alpha[0] + f.char_numb.to_s b.push(tmp_item) end puts b # to display results only, not really needed. =-=-=-=-=-=-=- ruby-1.9.3-p125 :020 > puts b a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 => nil -=-=-=-=-=-=-=-=- The cool thing is you can now do all kinds of multi sorts using this type of arrangement. Comes in handy where you have to sort multiple arrays and then merge those results at the end. Wayne