如何从这个Ruby哈希中提取值



我正在使用Foursquare API,我想从这个散列中提取"id"值

[{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twitter"=>"hitcrowd"}, "location"=>{"address"=>"1275 Glenlivet Drive", "crossStreet"=>"Route 100", "lat"=>40.59089895083072, "lng"=>-75.6291255071468, "postalCode"=>"18106", "city"=>"Allentown", "state"=>"Pa", "country"=>"United States", "cc"=>"US"}, "categories"=>[{"id"=>"4bf58dd8d48988d125941735", "name"=>"Tech Startup", "pluralName"=>"Tech Startups", "shortName"=>"Tech Startup", "icon"=>"https://foursquare.com/img/categories/shops/technology.png", "parents"=>["Professional & Other Places", "Offices"], "primary"=>true}], "verified"=>true, "stats"=>{"checkinsCount"=>86, "usersCount"=>4, "tipCount"=>0}, "url"=>"http://www.hitcrowd.com", "likes"=>{"count"=>0, "groups"=>[]}, "beenHere"=>{"count"=>0}, "storeId"=>""}] 

当我尝试使用['id']提取它时,我会得到这个错误can't convert Symbol into Integer。如何使用ruby提取值?此外,如何对每次提取"id"值的多个哈希执行此操作?

请原谅我缺乏经验。谢谢

它被封装在一个数组中,这就是[]在开始和结束时的含义。但看起来这个数组中只有一个对象,这就是您真正想要的散列。

所以假设你想要这个数组中的第一个对象:

mydata[0]['id'] # or mydata.first['id'] as Factor Mystic suggests

但通常当API返回Array时,是有原因的(它可能会返回很多结果,而不是一个结果),天真地从中提取第一个项可能不是你想要的。因此,在将数据硬编码到应用程序中之前,请确保您得到了真正期望的数据。

对于多个散列,如果你想id做一些事情(运行某种过程),那么

resultsArray.each do |person|
  id = person["id"] #then do something with the id
end

如果你只想得到一个包含id的数组,那么

resultsArray.map{|person| person["id"]}  
# ["4fe89779e4b09fd3748d3c5a", "5df890079e4b09fd3748d3c5a"]

要从数组中获取一个项目,请参阅Alex Wayne的答案

要获得id数组,请尝试:resultsArray.map { |result| result["id"] }

最新更新