Skip to content

Instantly share code, notes, and snippets.

@thomasfl
Created August 13, 2010 07:52
Show Gist options
  • Save thomasfl/522515 to your computer and use it in GitHub Desktop.
Save thomasfl/522515 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
# Danish norwegian sort order. Requires ruby 1.9 or better.
class String
# compares two strings based on a given alphabet
def cmp_loc(other, alphabet)
order = Hash[alphabet.each_char.with_index.to_a]
self.chars.zip(other.chars) do |c1, c2|
cc = (order[c1] || -1) <=> (order[c2] || -1)
return cc unless cc == 0
end
return self.size <=> other.size
end
end
class Array
# sorts an array of strings based on a given alphabet
def sort_loc(alphabet)
self.sort{|s1, s2| s1.cmp_loc(s2, alphabet)}
end
end
ALPHABETS = {
:danish_norwegian => 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpqRrSsTtUuVvWwXxYyZzÆæØøÅå',
:english => 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpqRrSsTtUuVvWwXxYyZzÆæØøÅå'
}
array_to_sort = ['abc', 'abd', 'øøø', 'Æææ', 'Øøø', 'bcd', 'Ååå', 'bcde', 'bde']
p array_to_sort.sort_loc(ALPHABETS[:danish_norwegian])
#=>["abc", "abd", "bcd", "bcde", "bde", "Æææ", "Øøø", "øøø", "Ååå"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment