Last active
January 11, 2016 02:58
-
-
Save at1as/bf25b23dbe0c8865e575 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
# A Natural Sort Algorithm in one line | |
ITEMS = %W(item1 item2 item11 item1 item20 item3 hello other_item other_item7 item) | |
TRAILING_NUM = /[0-9]*\Z/ | |
natural_sorted = ITEMS.sort.chunk{ |y| y.gsub(TRAILING_NUM, '') }.to_a.map{ |k_v| k_v[1] }.each{ |x| x.sort_by!{ |z| z.scan(TRAILING_NUM).first.to_i }}.flatten | |
puts natural_sorted | |
# => ["hello", "item", "item1", "item1", "item2", "item3", "item11", "item20", "other_item", "other_item7"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment