好吧,看来你的导师是对的:)
你可以这样做:
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 =