From: Rob Biedenharn Date: 2009-05-19T00:37:57+09:00 Subject: Re: Sorting numbers as strings On May 18, 2009, at 10:40 AM, Robert Klemme wrote: > 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:40:24 Temp$ cat srt.rb > puts DATA.sort_by {|s| s.scan(/\d+/).map {|x| x.to_i} } > > Kind regards > > robert > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ If you do need to consider things like "FastEthernet..." v. "GigabitEthernet...", then perhaps you want something like this which breaks the original string into digits and non-digits and converts the digits to be integers. puts DATA.sort_by {|s| s.scan(/\d+|\D+/).map {|x| x =~ /\d+/ ? x.to_i : x } } -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com