如何使用ruby从嵌套哈希中访问值

时间:2017-06-30 06:16:32

标签: ruby hash

{"headends"=>
  [{"headend"=>
     {"id"=>341766992,
      "headend_name"=>"Comcast Burlingame Digital",
      "dma_code"=>"807",
      "dma_rank"=>6,
      "system_name"=>"Comcast",
      "headend_city"=>"Burlingame",
      "headend_state"=>"CA",
      "headend_time_zone"=>"PT",
      "dma_name"=>"SAN FRANCISCO-OAK-SAN JOSE",
      "channel_device"=>"X",
      "country"=>"",
      "service_type"=>"CA"},
    "mso"=>{"id"=>341775346, "mso_name"=>"Comcast Cable Communications"},
    "postal_code"=>"94010",
    "device_id"=>"5b9a5042"}],
 "services"=>
  ["amazon",
   "directv",
   "hbogo",
   "hulu",
   "itunes",
   "itunes",
   "netflixusa",
   "showtime",
   "vudu",
   "youtube"],
 "postal_code"=>nil,
 "apps"=>
  ["cf528ea9",
   "ea0f81d1",
   "2ba2dc0e",
   "50107ad3",
   "3c103fa4",
   "692bea67",
   "557e96d5",
   "b2db5e2a",
   "0247ee5a",
   "f0ad77dc",
   "b24c00b1"]}

这是我的哈希,如何提取像" id" => 341766992," postal_code" =>" 94010"

等值

3 个答案:

答案 0 :(得分:2)

对于哈希的东西,例如{"foo"=>"bar", "baz"=>"blah"},使用密钥对其进行索引,例如myhash["foo"] # "baz"

对于数组,例如["hello", "world"],使用基于0的数字索引,例如myarray[1] # "world"

把这些东西放在一起挖掘你的结构,我在你的问题的编辑中打印出来:

data = {"headends"=>[{"headend"=>{"id"=>341766992, "headend_name"=>"Comcast Burlingame Digital", "dma_code"=>"807", "dma_rank"=>6, "system_name"=>"Comcast", "headend_city"=>"Burlingame", "headend_state"=>"CA", "headend_time_zone"=>"PT", "dma_name"=>"SAN FRANCISCO-OAK-SAN JOSE", "channel_device"=>"X", "country"=>"", "service_type"=>"CA"}, "mso"=>{"id"=>341775346, "mso_name"=>"Comcast Cable Communications"}, "postal_code"=>"94010", "device_id"=>"5b9a5042"}], "services"=>["amazon", "directv", "hbogo", "hulu", "itunes", "itunes", "netflixusa", "showtime", "vudu", "youtube"], "postal_code"=>nil, "apps"=>["cf528ea9", "ea0f81d1", "2ba2dc0e", "50107ad3", "3c103fa4", "692bea67", "557e96d5", "b2db5e2a", "0247ee5a", "f0ad77dc", "b24c00b1"]}

puts data["headends"][0]["headend"]["id"]
puts data["headends"][0]["postal_code"]

# Output:
# 341766992
# 94010

答案 1 :(得分:1)

在Ruby 2.3之前:

input['headends'].map do |e|
  [
    e['postal_code'], 
    *e['headend'].values_at(*%w|id|),
    *e['mso'].values_at(*%w|id|),
  ]
end

2.3 +

input['headends'].map do |e|
  [%w|postal_code|, %w|headend id|, %w|mso id|].map do |key|
    e.dig(*key)
  end
end

答案 2 :(得分:1)

您的问题已得到解答,但我发布此内容是为了更好地展示哈希的格式,并指出给出的示例可能会大幅缩小,但仍然可以提出相同的观点。

  h = { "headends"=>
          [ 
            { "headend"=> {
                "id"            =>341766992,
                "channel_device"=>"X",
                "service_type"  =>"CA"
              },
              "mso"=> {
                "id"      =>341775346,
                "mso_name"=>"Comcast Cable Communications"
              },
              "postal_code"=>"94010",
              "device_id"  =>"5b9a5042"
            }
          ]
      }

 h["headends"][0]["headend"]["id"] #=> 341766992
 h["headends"][0]["postal_code"]   #=> "94010"