Ruby 通过在嵌套哈希上迭代来构建新哈希

Ruby 通过在嵌套哈希上迭代来构建新哈希,ruby,hash,nested,Ruby,Hash,Nested,因此,我试图重新组织Google Places API中的一些数据,目前这些数据来自他们的API,如下所示: {"results"=> [ {"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=&g

因此,我试图重新组织Google Places API中的一些数据,目前这些数据来自他们的API,如下所示:

{"results"=> [
             {"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"5f212d158f4181db3ac0619fb3c52f36d4e276c2", "name"=>"Madeira Cafe", "reference"=>"CnRjAAAApaZWmTl5wOMtW49q3D1BLKAJ_M8lmZxaD6_-AU92qWfVZdokfTWOzlp5En_r9hSUHx-EeP71hzH7iDPYAGPtiqEAXvT4WcI3xlc5XUivenbQLw0j5MHW-ErL-Hbk4xB_by0OSsXCz9etNgkjbp0QCRIQ82Dgj-I3DAJqr7I3EwsFEhoUm2RXf2rCFlSuhfKjSsPuWKA2VGA",     {"results"=> [{"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}},
              "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
              "id"=>"11111111",
              "name"=>"Madeira Cafe",
              "reference"=>"xxxxx",
              "types"=>["restaurant", "food", "establishment"],
              "vicinity"=>"London"}]}
results_hash = {}
result.each do |geometry, location, id|
  results_hash[id] = geometry
end

p results_hash  
result_hash = {}
hash_from_google["results"].each do |result|
  result_hash[result["id"]] = {
    :name => result["name"], 
    :latitude => result["geometry"]["location"]["lat"],
    :longitude => result["geometry"]["location"]["lng"]
  }
end
result_hash["5f212..."] => {:name => "Madeira Cafe", :latitude => 51...., :longitude => -0.1....}
结果被放入一个具有一个键值的散列中-
“results”

其余数据嵌套在(我认为)内部,
“geometry”
是每条记录的第一条

我想得到的是一个整洁的散列,每个位置有一个ID,存储Lat/Lng和名称。。。因此,它可以存储和查询

我试过这样的方法:

{"results"=> [
             {"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"5f212d158f4181db3ac0619fb3c52f36d4e276c2", "name"=>"Madeira Cafe", "reference"=>"CnRjAAAApaZWmTl5wOMtW49q3D1BLKAJ_M8lmZxaD6_-AU92qWfVZdokfTWOzlp5En_r9hSUHx-EeP71hzH7iDPYAGPtiqEAXvT4WcI3xlc5XUivenbQLw0j5MHW-ErL-Hbk4xB_by0OSsXCz9etNgkjbp0QCRIQ82Dgj-I3DAJqr7I3EwsFEhoUm2RXf2rCFlSuhfKjSsPuWKA2VGA",     {"results"=> [{"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}},
              "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
              "id"=>"11111111",
              "name"=>"Madeira Cafe",
              "reference"=>"xxxxx",
              "types"=>["restaurant", "food", "establishment"],
              "vicinity"=>"London"}]}
results_hash = {}
result.each do |geometry, location, id|
  results_hash[id] = geometry
end

p results_hash  
result_hash = {}
hash_from_google["results"].each do |result|
  result_hash[result["id"]] = {
    :name => result["name"], 
    :latitude => result["geometry"]["location"]["lat"],
    :longitude => result["geometry"]["location"]["lng"]
  }
end
result_hash["5f212..."] => {:name => "Madeira Cafe", :latitude => 51...., :longitude => -0.1....}
但我不能让它工作。。。它总是输出零或者只是相同的散列

我希望这是有意义的,像往常一样,如果有人说“读这个”,这仍然是一个很大的帮助

谢谢


Charlie

您拥有的是一个哈希数组,即[{:geometry=>…,:id=>…},{:geometry=>…,:id=>…},等等]。我将提取数组,然后使用该方法迭代数组中的每个元素(即数组中的每个元素都是散列),并在运行时构建一个新的散列

在某种程度上:

# locations_array is [{"geometry"=>..., "icon"=>..., "id"=>..., etc}, {"geometry"=>..., "icon"=>..., "id"=>..., etc}, etc]
results_hash = locations_array.inject({}) do |hash, element|
  # extract the id key and the long/lat values
  # store them in the new hash
  hash[element[:id]] = element[:geometry]
  hash
end

如果您想要一个ID指向lat、lon和name的位置散列,可以执行以下操作:

{"results"=> [
             {"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"5f212d158f4181db3ac0619fb3c52f36d4e276c2", "name"=>"Madeira Cafe", "reference"=>"CnRjAAAApaZWmTl5wOMtW49q3D1BLKAJ_M8lmZxaD6_-AU92qWfVZdokfTWOzlp5En_r9hSUHx-EeP71hzH7iDPYAGPtiqEAXvT4WcI3xlc5XUivenbQLw0j5MHW-ErL-Hbk4xB_by0OSsXCz9etNgkjbp0QCRIQ82Dgj-I3DAJqr7I3EwsFEhoUm2RXf2rCFlSuhfKjSsPuWKA2VGA",     {"results"=> [{"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}},
              "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
              "id"=>"11111111",
              "name"=>"Madeira Cafe",
              "reference"=>"xxxxx",
              "types"=>["restaurant", "food", "establishment"],
              "vicinity"=>"London"}]}
results_hash = {}
result.each do |geometry, location, id|
  results_hash[id] = geometry
end

p results_hash  
result_hash = {}
hash_from_google["results"].each do |result|
  result_hash[result["id"]] = {
    :name => result["name"], 
    :latitude => result["geometry"]["location"]["lat"],
    :longitude => result["geometry"]["location"]["lng"]
  }
end
result_hash["5f212..."] => {:name => "Madeira Cafe", :latitude => 51...., :longitude => -0.1....}
现在您将得到如下结果:

{"results"=> [
             {"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"5f212d158f4181db3ac0619fb3c52f36d4e276c2", "name"=>"Madeira Cafe", "reference"=>"CnRjAAAApaZWmTl5wOMtW49q3D1BLKAJ_M8lmZxaD6_-AU92qWfVZdokfTWOzlp5En_r9hSUHx-EeP71hzH7iDPYAGPtiqEAXvT4WcI3xlc5XUivenbQLw0j5MHW-ErL-Hbk4xB_by0OSsXCz9etNgkjbp0QCRIQ82Dgj-I3DAJqr7I3EwsFEhoUm2RXf2rCFlSuhfKjSsPuWKA2VGA",     {"results"=> [{"geometry"=>{"location"=>{"lat"=>51.503815, "lng"=>-0.11007}},
              "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
              "id"=>"11111111",
              "name"=>"Madeira Cafe",
              "reference"=>"xxxxx",
              "types"=>["restaurant", "food", "establishment"],
              "vicinity"=>"London"}]}
results_hash = {}
result.each do |geometry, location, id|
  results_hash[id] = geometry
end

p results_hash  
result_hash = {}
hash_from_google["results"].each do |result|
  result_hash[result["id"]] = {
    :name => result["name"], 
    :latitude => result["geometry"]["location"]["lat"],
    :longitude => result["geometry"]["location"]["lng"]
  }
end
result_hash["5f212..."] => {:name => "Madeira Cafe", :latitude => 51...., :longitude => -0.1....}

本质上,只需从GooglePlacesAPI中得到的哈希中解析出所需内容。如果您在确定数据的设置方式或类似问题时遇到问题,请尝试将其复制到IRB中并进行处理-这样做可以非常容易地确定哈希的结构。

听起来您希望这样:

results_hash = result["results"].inject({}) { |h, res| h[res["id"]] = res["geometry"]; h }
这将为您提供以下哈希(使用
awesome\u print
打印):

您可能希望格式稍微好一点:

results_hash = result["results"].inject({}) do |h, res| 
  h[res["id"]] = res["geometry"]
  h
end
或者,如果您使用的是1.9:

results_hash = result["results"].each_with_object({}) do |res, h| 
  h[res["id"]] = res["geometry"]
end

似乎在那个上面出现了一个无法将字符串转换为整数(TypeError)的错误,有点奇怪,你们具体是在哪里得到这个错误的?如果我复制你从谷歌得到的散列(并称之为“hash_from_google”)并逐字运行我的代码,我会得到我随后显示的形式的结果…未定义的方法'each'代表nil:NilClass(NoMethodError)。each do-这很奇怪,do是通用方法?!在这种情况下,来自谷歌的
hash\u
为零,或者来自谷歌[“结果”]的
hash\u为零。确保修改代码,以便将google的
hash\u设置为调用google Places API的完整结果。(例如,
hash_from_google={“results”=>[{“geometry”=>…}
)哦,我的天啊!请不要理我,我太傻了,我把它指向了错误的东西!该休息了!谢谢!!嘿,谢谢!你能想出我把它当作错误的原因吗?我想这可能是我的控制台,因为我刚刚得到了一个“each”其他代码错误…
”:未定义的方法
inject'用于nil:NilClass(NoMethodError)@Charlie:是否有效?如果有效,请您投票并/或接受此答案,以便其他人知道这是您要找的?嗨,在我使用此解决方案时,它给出的结果类似于“21321”=>{“name”=>测试,“lat”=>223123,“lng”=>221312}我如何将第一位放入{}中,使其id=>2211?如果我使用上面的例子,它只会产生一个结果,,,我猜是因为它没有迭代任何东西?@Charlie Davis:那么你想要什么作为键?对不起,我昨天离线了,我想得到的是{“id”:132312321,“lat”:23.232323,“lng”:-0.22222}我正在使用.to_json将其转换为json格式,但需要使用API括号中的所有内容