当我写下这段文字时,我以为我是一个 Ruby 巨人:
# having this hash
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
# country_id comes from input
country_name = (hash.select { |k,v| v == country_id.to_i }.first || []).first
它确实正确提取了国家/地区名称,并且如果未找到国家/地区也不会失败。
我对此非常满意。
然而我的导师说它可以/应该在可读性、长度和性能方面进行优化!
还有什么比这更清晰/更快的呢?
请指教
好吧,看来你的导师是对的:)
你可以这样做:
hash.invert[ country_id.to_i ] # will work on all versions
或者,按照@littlecegian的建议
hash.key( country_id.to_i ) # will work on 1.9 only
或者,按照@steenslag的建议
hash.index( country_id.to_i ) # will work on 1.8 and 1.9, with a warning on 1.9
完整示例:
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
%w[2 3 1 blah].each do |country_id|
# all versions
country_name = hash.invert[ country_id.to_i ]
# 1.9 only
country_name = hash.key( country_id.to_i )
# 1.8 and 1.9, with a warning on 1.9
country_name = hash.index( country_id.to_i )
printf "country_id = %s, country_name = %s\n", country_id, country_name
end
将打印:
country_id = 2, country_name = France
country_id = 3, country_name = USA
country_id = 1, country_name = Portugal
country_id = blah, country_name =
看到它运行
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)