Home > Uncategorized > Ruby Sorting

Ruby Sorting

A rather neat little piece of code I ran across for “human” sorting. Given an array of picture names:

%w[picture3 picture20 picture1004 picture1].sort_by {|item| item.scan(/[0-9]+|[^0-9]+/).map {|s| s[/[^0-9]/] ? s : s.to_i} }

Split each string up into runs of digits or runs of non-digits, convert the digit strings to integers, and sort array-wise (component by component).

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.