For my application(Ruby on Rails) i have country select box for the signup page. These countries are localized into different language. But i couldnt find a way to sort them, based on the language in which its localized. At present i have sorted it out based on english only. Is there a way to sort the country names based on the locale? i.e the order of the countries should change(ascending order) according to the language its localised. Thanks..
but , say if the lang is chinese, how to sort it based on chinese?
railscoder
2010-05-06 12:26:24
+2
A:
You can make a custom String
comparison method, based on a given alphabet, something like this (works in Ruby 1.9):
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
array_to_sort = ['abc', 'abd', 'bcd', 'bcde', 'bde']
ALPHABETS = {
:language_foo => 'abcdef',
:language_bar => 'fedcba'
}
p array_to_sort.sort_loc(ALPHABETS[:language_foo])
#=>["abc", "abd", "bcd", "bcde", "bde"]
p array_to_sort.sort_loc(ALPHABETS[:language_bar])
#=>["bde", "bcd", "bcde", "abd", "abc"]
And then provide alphabetical orders for every language you want to support.
Mladen Jablanović
2010-05-06 11:18:48