ryanb (owner)

Forks

Revisions

gist: 142329 Download_button fork
public
Public Clone URL: git://gist.github.com/142329.git
Embed All Files: show embed
finder_sort.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Mimic Mac OS X Finder's sort by name.
class Array
  def finder_sort
    sort_by do |str|
      punctuation = %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ *] + ['\\'] + %w[& # % + < = > | ~ $]
      str.to_s.gsub(/\d+|[^a-z\s]/i) do |match|
        if punctuation.include? match
          "1".rjust(200 - punctuation.index(match), "0")
        elsif match =~ /^0+$/ # make an exception for zeros
          "1".rjust(101, "0")
        elsif match =~ /^\d+$/
          match.rjust(100, "0")
        else
          "1".rjust(102, "0")
        end
      end.downcase
    end
  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 ( ) * + , ? & @ - 0 ; < = \\ ] ^ _ | } ~] + [" "]
    expected = [" "] + %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ * \\ & # % + < = > | ~ $ 0 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
  
  def test_multiple_spaces
    assert_equal ["foo bar", "foo 0"], ["foo 0", "foo bar"].finder_sort
  end
  
  def test_zeros_after_punctuation
    assert_equal %w[$ 000 001], %w[000 $ 001].finder_sort
  end
  
  def test_sort_numeric_with_zero
    assert_equal ["5", "10"], ["10", "5"].finder_sort
  end
end