Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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