🕷 zenspider.com

by ryan davis

Looking for the Ruby Quickref?

How #ruby-lang approximates the corporate environment

Published 2006-05-06 @ 03:17

Tagged ruby, thoughts

Original Request:

I’d like to sort an array of strings numerically…


… but that doesn’t handle letters (non-number strings) … mine was shorter, but it uses an intermediate variable … nice, but how do you get the digits before the letters?

My final version:

%w(z A 1 10 2 b).sort_by { |s| [ s[0], s.to_i, s ] }



kodis did a good job pointing out that I shouldn’t blog at 2am. The above code is buggy. Namely, the first term in the sort_by is flat out wrong and was a quick add right at the end that I didn’t do a good job of testing. So, the elegant version is:

%w(z A 1 10 2 b).sort_by { |s| [ s.to_i, s ] }

but the one that will sort numbers first (no idea why still, but hey) is:

%w(z A 1 10 2 b).sort_by { |s| [ s =~ /^\d/ ? 1 : 2, s.to_i, s ] }

still, even that ugly sort_by is vastly better than my first attempt:

%w(z a 1 10 2 b).map {|o| Integer(o) rescue o }.partition { |o|
  Fixnum === o }.map { |a| a.sort }.flatten.map { |o| o.to_s }