当我写这篇oneliner时,我以为我是一个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
它确实正确提取了国家/地区名称,如果找不到国家/地区,则不会失败。
我对它非常满意。
但是我的导师说它可以/应该在可读性,长度和性能方面进行优化!
什么比这更清楚/更快?
请告知
答案 0 :(得分:9)
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 =
答案 1 :(得分:8)
如果是ruby 1.9.3,你可以使用hash.key(country_id.to_i)
答案 2 :(得分:5)
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
puts hash.invert[3] # "USA"
答案 3 :(得分:2)
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
hash.index(2) # => "France"
是Ruby 1.8.x的方式。 index
method在1.9中已弃用,并替换为key
方法。