Reputation: 653
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..
Upvotes: 4
Views: 2066
Reputation: 725
Sometime ago twitter released a library which can nicely take care of it in Ruby for multiple language and it actually works https://github.com/twitter/twitter-cldr-rb#sorting-collation . It is also very nice that they provided a higher level way for sorting as well as low-level which can just compare two string for given locale. This allowed me to get rid of git://github.com/k3rni/ffi-locale.git which I was using so far for sorting string in a locale-aware way.
Upvotes: 2
Reputation: 44080
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.
Upvotes: 3
Reputation: 46904
Maybe you can translate all and sort it after this translation.
Upvotes: -1