[英]in Ruby, how to extract a key from the Hash having the value
i thought i'm a Ruby giant when i wrote this oneliner: 当我写这个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
it does correctly extract the country name and does Not fail if country not found. 它确实正确提取国家名称,如果找不到国家,则不会失败。
i'm totally pleased with it. 我很满意。
however my tutor says it can/should be optimized in terms of readability, length and performance! 但是我的导师说它可以/应该在可读性,长度和性能方面进行优化!
what can be clearer/faster than this? 什么比这更清楚/更快?
please advise 请指教
well, seems your tutor is right :) 好吧,看来你的导师是对的:)
you can do like this: 你可以这样做:
hash.invert[ country_id.to_i ] # will work on all versions
or, as suggested by @littlecegian 或者,正如@littlecegian所建议的那样
hash.key( country_id.to_i ) # will work on 1.9 only
or, as suggested by @steenslag 或者,正如@steenslag所建议的那样
hash.index( country_id.to_i ) # will work on 1.8 and 1.9, with a warning on 1.9
Full example: 完整示例:
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
will print: 将打印:
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"
is the Ruby 1.8.x way. 是Ruby 1.8.x的方式。 The
index
method is deprecated in 1.9 and being replaced with the key
method. index
方法在1.9中已弃用,并被替换为key
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.