我有一个哈希值,它是在进行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"]
任何人对我缺少的东西都有任何提示吗?
答案 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"]