简体   繁体   English

如何从该Ruby哈希值中提取值?

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

I'm using the Foursquare API, and I want to extract the "id" value from this 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"=>""}] 

When I try to extract it by using ['id'] , I get this error can't convert Symbol into Integer . 当我尝试使用['id']提取它时,出现此错误can't convert Symbol into Integer How do I extract the value using ruby? 如何使用红宝石提取价值? Also, how do I do this for multiple hashes extracting the "id" value each time? 另外,对于每次提取“ id”值的多个哈希,我该怎么做?

Please pardon my inexperience. 请原谅我的经验。 Thanks! 谢谢!

It's wrapped in an array, that's what the [ and ] mean on the start and end. 它包装在一个数组中,这就是[]在开始和结束处的含义。 But it also looks like this array only one object in it, which is the hash you really want. 但是它看起来也像这个数组中只有一个对象,这是您真正想要的哈希。

So assuming you want the first object in this array: 因此,假设您想要此数组中的第一个对象:

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

But usually when an API returns an Array there is a reason (it might return many results instead of just one), and naively plucking the first item from it my not be what you want. 但是通常,当API返回数组时,有一个原因(它可能返回许多结果而不是仅仅返回一个结果),并且天真地从中选择第一项,这并不是您想要的。 So be sure you are getting the kind of data you really expect before hard coding this into your application. 因此,在将其硬编码到应用程序中之前,请确保已获取到您真正期望的数据类型。

For multiple hashes, if you want to do something with the id (run a procedure of some kind) then 对于多个散列,如果您想使用 id 做某事 (运行某种过程),则

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

If you want to just get an array containing the ids then 如果您只想获取包含ID的数组,

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

To just grab the one item from the array, see Alex Wayne 's answer 要仅从数组中获取一项,请参阅Alex Wayne的答案

To get an array of ids, try: resultsArray.map { |result| result["id"] } 要获取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