我以为我写这句话时我是一个红宝石巨人:
# 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 = %sn", 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 =
看到它在这里运行
如果是ruby 1.9.3,则可以使用hash.key(country_id.to_i)
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
puts hash.invert[3] # "USA"
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
hash.index(2) # => "France"
是Ruby 1.8.x方式。index
方法在1.9中被弃用,并用key
方法替换。