Skip to content

Instantly share code, notes, and snippets.

@aitor
Forked from ryanb/finder_sort.rb
Created July 7, 2009 20:38
Show Gist options
  • Save aitor/142349 to your computer and use it in GitHub Desktop.
Save aitor/142349 to your computer and use it in GitHub Desktop.
# Mimic Mac OS X Finder's sort by name.
class Array
def finder_sort
sort { |a, b| a.to_finder_sort <=> b.to_finder_sort }
end
end
class String
def to_finder_sort
result = self.dup
order = %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ * \\ & # % + < = > | ~ $] + [/[^0-9a-z\s]/i, /\d+/]
order.reverse.each_with_index do |target, index|
result.gsub!(target) { |m| m.rjust(100 + index) }
end
result.downcase
end
end
require "test/unit"
class FinderSortTest < Test::Unit::TestCase
def test_ignore_case
assert_equal %w[rob Robo robot], %w[robot Robo rob].finder_sort
end
def test_sort_numeric
assert_equal %w[19 21 119], %w[119 19 21].finder_sort
end
def test_sort_numeric_with_spaces
assert_equal ["12 19", "12 119"], ["12 119", "12 19"].finder_sort
end
def test_punctuation
given = %w[% ! " # $ ' ` { [ > a ( ) * + , ? & @ - 1 ; < = \\ ] ^ _ | } ~] + [" "]
expected = [" "] + %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ * \\ & # % + < = > | ~ $ 1 a]
assert_equal expected.to_s, given.finder_sort.to_s
end
def test_unknown_punctuation
assert_equal %w[` $ : 1 a], %w[: 1 a ` $].finder_sort
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment