我做了一个涉及
的小项目如果用户输入+44,则应提取国家和国家/地区缩写
我想知道实现这个的最佳方法是什么?我应该创造3个不同的哈希?或使用嵌套哈希?
答案 0 :(得分:6)
在重新发明轮子之前,您应该检查现有的解决方案,例如countries gem:
c.number #=> "840"
c.alpha2 #=> "US"
c.alpha3 #=> "USA"
c.country_code #=> "1"
c.national_destination_code_lengths #=> 3
c.national_number_lengths #=> 10
c.international_prefix #=> "011"
c.national_prefix #=> "1"
答案 1 :(得分:0)
假设您正在询问,因为您需要能够根据任何字段查找数据,您可以使用以下内容将记录映射到三个不同的哈希值,其中每个哈希都由相关字段编制索引
country_codes, names, dial_codes = [
{ country_code: "GB", name: "United Kingdom", dial_code: "44" },
{ country_code: "AU", name: "Australia", dial_code: "61" },
{ country_code: "IT", name: "Italy", dial_code: "39" }
].inject([{}, {}, {}]) do |(cc, n, dc), record|
[
cc.merge(record[:country_code] => record),
n.merge(record[:name] => record),
dc.merge(record[:dial_code] => record)
]
end
p country_codes["AU"]
# => { country_code: "AU", name: "Australia", dial_code: "61" }
p dial_codes["44"]
# => { country_code: "GB", name: "United Kingdom", dial_code: "44" }
另请注意,英国的官方国家/地区代码为GB,而非英国。令我感到困惑,我知道。