🕷 zenspider.com

by ryan davis



sitemap
Looking for the Ruby Quickref?

Array#natural_sort

Published 2012-01-30 @ 15:02

Tagged ruby, thoughts

Sitting in omnifocus for ~4 years…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'fileutils'

20.times do |n|
  FileUtils.touch "f#{n}.txt"
end

p Dir["f*.txt"].sort
# => ["f0.txt", "f1.txt", "f10.txt", "f11.txt", ..., "f2.txt", "f3.txt", ...]

class Array
  def human_sort
    sort_by { |item| item.to_s.split(/(\d+)/).map { |e| [e.to_i, e] } }
  end
end

p Dir["f*.txt"].human_sort
# => ["f0.txt", "f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt", "f6.txt", ...]