当我写这个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
Run Code Online (Sandbox Code Playgroud)
它确实正确提取国家名称,如果找不到国家,则不会失败.
我很满意.
但是我的导师说它可以/应该在可读性,长度和性能方面进行优化!
什么比这更清楚/更快?
请指教
小智 9
好吧,看来你的导师是对的:)
你可以这样做:
hash.invert[ country_id.to_i ] # will work on all versions
Run Code Online (Sandbox Code Playgroud)
或者,正如@littlecegian所建议的那样
hash.key( country_id.to_i ) # will work on 1.9 only
Run Code Online (Sandbox Code Playgroud)
或者,正如@steenslag所建议的那样
hash.index( country_id.to_i ) # will work on 1.8 and 1.9, with a warning on 1.9
Run Code Online (Sandbox Code Playgroud)
完整示例:
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
Run Code Online (Sandbox Code Playgroud)
将打印:
country_id = 2, country_name = France
country_id = 3, country_name = USA
country_id = 1, country_name = Portugal
country_id = blah, country_name =
Run Code Online (Sandbox Code Playgroud)
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
puts hash.invert[3] # "USA"
Run Code Online (Sandbox Code Playgroud)