["a", "c", "b", "1", "10", "3", "thing4", "thing3", "thing30", "thing2"]
We needed the text only strings first and the strings with numbers in them sorted by their numbers. The example arrays explain it better. Here's what I came up with:
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
class Array | |
def natural_sort | |
just_letters = self.select{|el| el =~ /^[a-zA-Z]+$/} | |
numbers = self - just_letters | |
just_letters.sort + numbers.sort{|x,y| x.gsub(/[a-zA-Z]+/, '').to_i <=> y.gsub(/[a-zA-Z]+/, '').to_i} | |
end | |
end |
This will sort that array so it comes out looking like this:
["a", "b", "c", "1", "thing2", "3", "thing3", "thing4", "10", "thing30"]
Pretty, huh?