From: Alan Davies Date: 2003-09-16T02:07:51+09:00 Subject: Re: Natural order sort >>split(/(\d+)/) Interesting. I always assumed split filtered out the matching sections, but it appears that you can make them appear in the resulting array by putting brackets round the relevant bit in the regexp. This isn't mentioned in the Pragmatic Programmers book. Sabby and Tabby wrote: > Alan Davies wrote: > > >>I've written a natural order comparison funtion for the String class. >>This was based on Martin Pool's "Natural Order String Comparison" which >>was written in C. >>http://sourcefrog.net/projects/natsort/ >> >>The basic premise is that "something1" < "something2" < "something10" >>which does not follow if you use alphabetical sorting. >> >>I thought I'd post it here in case anyone was interested in it. I'd >>also be grateful of any comments about improving it in any way. > > > Nifty and new in Ruby 1.8 is #sort_by: > > def String.natural_order(nocase=false) > proc do |str| > i = true > str = str.upcase if nocase > str.gsub(/\s+/, '').split(/(\d+)/).map {|x| (i = !i) ? x.to_i : x} > end > end > > puts %w[ foo1 12 foo10 foo2 ].sort_by(&String.natural_order)