From: Robert Klemme Date: 2009-05-18T23:40:46+09:00 Subject: Re: Sorting numbers as strings 2009/5/18 Jack Bauer : > I'm trying to sort some strings containing numbers. The strings > themselves can't be changed (they're items being pulled from a DB.) This > is an example of some of the things I need to sort. First is how I > wanted them sorted: > > FastEthernet0/1 > FastEthernet0/10 > FastEthernet0/11 > FastEthernet0/12 > FastEthernet0/13 > FastEthernet0/2 > FastEthernet0/3 > FastEthernet0/4 > FastEthernet0/5 > FastEthernet0/6 > FastEthernet0/7 > FastEthernet0/8 > FastEthernet0/9 > ... > > I need to get it like this: > FastEthernet0/1 > FastEthernet0/2 > FastEthernet0/3 > FastEthernet0/4 > FastEthernet0/5 > FastEthernet0/6 > FastEthernet0/7 > FastEthernet0/8 > FastEthernet0/9 > FastEthernet0/10 > FastEthernet0/11 > FastEthernet0/12 > FastEthernet0/13 > > Then they could turn into FastEthernet1/1, etc. Also, the name doesn't > really matter as it could have FastEthernet, another name, or none at > all and just be 0/1 or whatever. > > I'm guessing something like a regex to strip non-numbers so > FastEthernet0/1 becomes 01 then sort numerically, but that wouldn't help > if I have FastEthernet0/1, GigabitEthernet0/1, and FastEthernet0/2 since > it would come out in an incorrect order (01, 01, 02 instead of 01, 02, > 01 because of the F and G alphabetical sort.) > > Any ideas of the best way to go about this? 16:39:42 Temp$ ruby19 srt.rb FastEthernet0/1 FastEthernet0/2 FastEthernet0/3 FastEthernet0/4 FastEthernet0/5 FastEthernet0/6 FastEthernet0/7 FastEthernet0/8 FastEthernet0/9 FastEthernet0/10 FastEthernet0/11 FastEthernet0/12 FastEthernet0/13 16:40:24 Temp$ cat srt.rb puts DATA.sort_by {|s| s.scan(/\d+/).map {|x| x.to_i} } __END__ FastEthernet0/1 FastEthernet0/10 FastEthernet0/11 FastEthernet0/12 FastEthernet0/13 FastEthernet0/2 FastEthernet0/3 FastEthernet0/4 FastEthernet0/5 FastEthernet0/6 FastEthernet0/7 FastEthernet0/8 FastEthernet0/9 16:40:28 Temp$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/