将哈希区域名称的第一位转换为纯文本,即将en_GB转换为rubying on rails中的英国

时间:2013-02-09 19:28:09

标签: ruby-on-rails ruby facebook-graph-api

我有这个哈希,它的第一部分我需要转换为纯文本,例如en_GB 将是英国。这是我从Facebook api获得的示例响应。

    {"en_GB"=>6836, "en_US"=>3414, "it_IT"=>120, "es_LA"=>37, "fr_FR"=>24, "zh_TW"=>18, "pt_BR"=>18, "de_DE"=>16, "hr_HR"=>15, "pl_PL"=>12, "es_ES"=>12, "ru_RU"=>10, "id_ID"=>9, "el_GR"=>8, "ar_AR"=>8, "th_TH"=>8, "tr_TR"=>8, "bg_BG"=>7, "lv_LV"=>6, "zh_CN"=>6, "cs_CZ"=>5, "ro_RO"=>4, "pt_PT"=>4, "en_PI"=>4, "he_IL"=>3, "sk_SK"=>3, "hu_HU"=>3, "mk_MK"=>3, "nl_NL"=>2, "sv_SE"=>2, "zh_HK"=>2, "lt_LT"=>2, "nl_BE"=>2, "fb_LT"=>1, "en_IN"=>1, "sl_SI"=>1, "sq_AL"=>1, "ko_KR"=>1, "da_DK"=>1, "ka_GE"=>1, "cy_GB"=>1, "mr_IN"=>1, "sr_RS"=>1, "nb_NO"=>1}

有人知道如何将其转换为纯文本吗?

1 个答案:

答案 0 :(得分:2)

在rails应用程序的/config/locales/en.yml中设置区域设置数据

en:
  en_GB: "Great Britain"
  en_US: 'United States'
  ..so on..

然后

fb_response = {"en_GB"=>6836, "en_US"=>3414, "it_IT"=>120, "es_LA"=>37, "fr_FR"=>24, "zh_TW"=>18, "pt_BR"=>18, "de_DE"=>16, "hr_HR"=>15, "pl_PL"=>12, "es_ES"=>12, "ru_RU"=>10, "id_ID"=>9, "el_GR"=>8, "ar_AR"=>8, "th_TH"=>8, "tr_TR"=>8, "bg_BG"=>7, "lv_LV"=>6, "zh_CN"=>6, "cs_CZ"=>5, "ro_RO"=>4, "pt_PT"=>4, "en_PI"=>4, "he_IL"=>3, "sk_SK"=>3, "hu_HU"=>3, "mk_MK"=>3, "nl_NL"=>2, "sv_SE"=>2, "zh_HK"=>2, "lt_LT"=>2, "nl_BE"=>2, "fb_LT"=>1, "en_IN"=>1, "sl_SI"=>1, "sq_AL"=>1, "ko_KR"=>1, "da_DK"=>1, "ka_GE"=>1, "cy_GB"=>1, "mr_IN"=>1, "sr_RS"=>1, "nb_NO"=>1}

fb_response = Hash[fb_response.map {|k, v| [t(k.to_sym), v] }]

map返回新数组,其中每个元素运行一次块的结果,Hash []创建一个新的哈希,返回的数组中每个[k,v]对。在块中,我们将密钥转换为符号,并将其作为#translate传递给t别名,将其转换为当前区域设置。