簡體   English   中英

在Ruby中,如何從具有該值的Hash中提取密鑰

[英]in Ruby, how to extract a key from the Hash having the value

當我寫這個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

它確實正確提取國家名稱,如果找不到國家,則不會失敗。

我很滿意。

但是我的導師說它可以/應該在可讀性,長度和性能方面進行優化!

什么比這更清楚/更快?

請指教

好吧,看來你的導師是對的:)

你可以這樣做:

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 =

看到它在這里運行

如果它是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方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM