2010-05-06 62 views
3

对于我的应用程序(Ruby on Rails),我有注册页面的国家/地区选择框。这些国家被本地化为不同的语言。但我无法找到一种方法来对其进行排序,基于其本地化语言。目前我已经根据英文对其进行了整理。有没有办法根据语言环境对国家名称进行排序?即国家的顺序应根据其本地化的语言而改变(升序)。 谢谢..ruby​​中基于区域设置的排序功能

+0

可能重复:http://stackoverflow.com/questions/2360281/alphabetize-arabic-and-japanese-text-that-is-in-unicode – 2010-05-09 23:58:49

回答

-1

也许你可以翻译全部并在此翻译后对其进行排序。

+0

但是,如果lang是中文,那么应该如何对它进行排序对中国人? – anusuya 2010-05-06 12:26:24

3

您可以自定义String比较法,根据给定的字母,这样的事情(在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"] 

然后你要支持每一种语言提供按字母顺序排列的订单。

1

某个时间以前,twitter发布了一个库,可以在Ruby中很好地处理多种语言,它实际上可以工作https://github.com/twitter/twitter-cldr-rb#sorting-collation。他们也提供了更高层次的排序方法以及低层次的方法,只需比较给定语言环境中的两个字符串,这也是非常好的。这让我摆脱了git://github.com/k3rni/ffi-locale.git,到目前为止我已经使用了一种可识别语言环境的字符串排序方式。