Skip to content

Instantly share code, notes, and snippets.

@henrik
Forked from bradediger/gist:1206702
Created October 18, 2011 17:28
Show Gist options
  • Save henrik/1296042 to your computer and use it in GitHub Desktop.
Save henrik/1296042 to your computer and use it in GitHub Desktop.
# Sort lexicographically, but sorting numbers into their proper position.
#
class Array
def sort_preserving_numbers
sort_by { |x|
x.split(/(\d+)/).
map { |piece| piece.match(/\d/) ? piece.to_i : piece }
}
end
end
# USAGE:
p array = (7..12).map{ |x| "I have #{x} apples" }
p 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"]
p 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