Created
September 9, 2011 16:44
-
-
Save bradediger/1206702 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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