Skip to content

Instantly share code, notes, and snippets.

@bradediger
Created September 9, 2011 16:44
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bradediger/1206702 to your computer and use it in GitHub Desktop.
# Sort lexicographically, but sorting numbers into their proper position.
# Ruby 1.9 only as the zero-width lookbehind assertions require Oniguruma.
#
class Array
def sort_preserving_numbers
sort_by { |x|
x.split(%r{(?<=\D)(?=\d)|(?<=\d)(?=\D)}).
map { |piece| (piece =~ /\A\d+\z/) ? piece.to_i : piece }
}
end
end
# USAGE:
array = (7..12).map{ |x| "I have #{x} apples" }
array.sort
# => ["I have 10 apples", "I have 11 apples", "I have 12 apples", "I have 7 apples", "I have 8 apples", "I have 9 apples"]
array.sort_preserving_numbers
# => ["I have 7 apples", "I have 8 apples", "I have 9 apples", "I have 10 apples", "I have 11 apples", "I have 12 apples"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment