Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created July 7, 2009 20:21
Show Gist options
  • Save ryanb/142329 to your computer and use it in GitHub Desktop.
Save ryanb/142329 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment