簡體   English   中英

如何從該Ruby哈希值中提取值?

[英]How do I extract a value from this Ruby hash?

我正在使用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 如何使用紅寶石提取價值? 另外,對於每次提取“ id”值的多個哈希,我該怎么做?

請原諒我的經驗。 謝謝!

它包裝在一個數組中,這就是[]在開始和結束處的含義。 但是它看起來也像這個數組中只有一個對象,這是您真正想要的哈希。

因此,假設您想要此數組中的第一個對象:

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

但是通常,當API返回數組時,有一個原因(它可能返回許多結果而不是僅僅返回一個結果),並且天真地從中選擇第一項,這並不是您想要的。 因此,在將其硬編碼到應用程序中之前,請確保已獲取到您真正期望的數據類型。

對於多個散列,如果您想使用 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"] } resultsArray.map { |result| result["id"] }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM