-
-
Save henrik/1296042 to your computer and use it in GitHub Desktop.
This file contains 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. | |
# | |
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