迭代Ruby中的哈希数组(解析的JSON)

时间:2018-04-15 06:08:33

标签: arrays json ruby object each

我有一个哈希值,它是在进行API调用并通过JSON.parse运行时创建的:

{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}

我试图从每个对象中获取所有的zipcodes并将它们放入一个数组中:

zipcode_array = Array.new

我尝试过以下代码:

locations.each do |zipcode|
    zipcode_array.push(['results'][i]['zip'])
end

我希望我的最终输出是:

zipcode_array = ["08225", "08221"]

任何人对我缺少的东西都有任何提示吗?

2 个答案:

答案 0 :(得分:5)

您的代码似乎缺少i变量(索引),但实际上您并不需要它,因为您始终可以使用map函数来实现惯用的Ruby代码:

require "json"

response = '{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}'

parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }

答案 1 :(得分:1)

而不是使用each,您可以使用map函数来实现此目的。

response[:results].map{|x| x[:zip]}

这将为您提供数组中的结果,即

["08225", "08221"]