在Ruby中,如何从哈希中提取具有该值的密钥 [英] in Ruby, how to extract a key from the Hash having the value

查看:105
本文介绍了在Ruby中,如何从哈希中提取具有该值的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #拥有这个哈希值
哈希值= {'葡萄牙'=> 1,'France'=> 2,'USA'=> 3}

#country_id来自输入
country_name =(hash.select {| k,v | v == country_id.to_i} .first || [])。first

它能够正确提取国家名称,并且在国家/地区未找到时不会失败。



我对此很满意。

但是我的导师说可以/应该在可读性,长度和性能方面进行优化! / p>

有什么可以比这更清晰/更快的?

请指教



您可以这样做:

b
$ b

  hash.invert [country_id.to_i]#将适用于所有版本

或者,如@littlecegian所示

  hash.key(country_id.to_i )#只会在1.9 

或@steenslag

建议

  hash.index(country_id.to_i)#将在1 .8和1.9,并在1.9 

上发出警告完整示例:

  hash = {'Portugal'=> 1,'France'=> 2,'USA'=> 3} 

%w [2 3 1 blah] .each do | country_id |

#所有版本
country_name = hash.invert [country_id.to_i]

#1.9 only
country_name = hash.key(country_id.to_i)

#1.8和1.9,并在1.9
country_name = hash.index(country_id.to_i)


printfcountry_id =%s ,country_name =%s\\\
,country_id,country_name
结束

会打印:

  country_id = 2,country_name =法国
country_id = 3,country_name =美国
country_id = 1, country_name = Portugal
country_id = blah,country_name =



看到它正在运行 here


i thought i'm a Ruby giant when i wrote this oneliner:

# 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

hash.key( country_id.to_i )    # will work on 1.9 only

or, as suggested by @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 =

see it running here

这篇关于在Ruby中,如何从哈希中提取具有该值的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆