ruby-on-rails - ruby 中基于语言环境的排序功能

标签 ruby-on-rails ruby internationalization

对于我的应用程序(Ruby on Rails),我在注册页面有国家/地区选择框。这些国家被本地化为不同的语言。但是我找不到一种方法来根据其本地化的语言对它们进行排序。目前我只根据英文整理出来。有没有办法根据语言环境对国家/地区名称进行排序?即国家的顺序应该根据其本地化的语言改变(升序)。 谢谢..

最佳答案

您可以根据给定的字母表制作自定义的 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"]

然后为您要支持的每种语言提供字母顺序。

关于ruby-on-rails - ruby 中基于语言环境的排序功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2779880/

相关文章:

sql - rails : Find the "has_one" record that doesn't have one

ruby-on-rails - 使用 Rails 在公共(public)文件夹中本地提供 1GB 文件

ruby - 使用 **自定义** Ruby 方法查找质数

ruby - 在 Ruby 中,如何读取放置在程序/脚本本身中的数据?

mysql - 在 Windows 7 64 位上使用 mysql2 安装 ruby​​ 在 rails s 上返回错误

ruby-on-rails - 在 mesos 集群上连接 rails 和存储服务

ruby-on-rails - NoMethodError(未定义方法 `charset=' 为 nil :NilClass): when sending email with rails

java - 来自多个属性文件的 Spring i18n 本地化

xml - 使用非 ASCII(自然语言)XML 标签是否合适?

android - Google Maps Android API v2,标记标题/fragment 错误显示