Skip to content

Instantly share code, notes, and snippets.

@at1as
Last active January 11, 2016 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save at1as/bf25b23dbe0c8865e575 to your computer and use it in GitHub Desktop.
Save at1as/bf25b23dbe0c8865e575 to your computer and use it in GitHub Desktop.
# 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