如何在Ruby哈希表中搜索值?

时间:2017-07-02 16:37:42

标签: ruby

area_dictionary = {
  "Alabama" => "205",
  "Alaska" => "907",
  "American Samoa" =>"684",
  "Arizona" => "480",
  "Arkansas" => "479",
  "California" => "209",
  "Colorado" => "303",
  "Connecticut" => "203",
  "Delaware" => "302",
  "Florida" => "239",
  "Georgia" => "229",
  "Guam" => "671",
  "Hawaii" => "808"
}

def get_city_name(hash,key)
    hash.each{|k,v|puts k if v==key}
end
    puts"Please enter the code for which you want to find the city?"
    code = gets.chomp
    if area_dictionary.include?(code)#getting trouble from here
      puts "The city for #{code}is#{get_city_name(area_dictionary,code)}"
    end

2 个答案:

答案 0 :(得分:2)

如果您要查找值的键,可以使用以下命令:

area_dictionary.invert['239']
=> "Florida"

如果您只是想获取给定密钥的值,可以使用以下内容:

area_dictionary['Florida']
=> "239"

答案 1 :(得分:0)

一些不言自明的例子

area_dictionary["Alaska"]
 => "907"
area_dictionary["Alaskaaaa"]
 => nil
area_dictionary.fetch("Alaska")
 => "907"
area_dictionary.fetch("Alaskaaaa")
 KeyError: key not found: "Alaskaaaa"
    from (irb):5:in `fetch'
    from (irb):5
    from /usr/local/bin/irb:11:in `<main>'
area_dictionary.fetch("Alaskaaaa", 10)
 => 10
area_dictionary.values_at("Alabama", "Alaska")
 => ["205", "907"]