繁体   English   中英

如何从红宝石的哈希数组中获取键/值对?

[英]How do you grab a key/value pair from an array of hashes in ruby?

我有一系列哈希(或者至少我认为它们是哈希),我需要为每个哈希提取ID。 我确信ruby有一些快速的方法可以做到这一点...我只是想不通。

我不想遍历数组并构建一个新数组。

[
  [
    {
      "bio": "I am a tech geek who loves starting up companies. While I was in college, I founded Squeeze My Tees",
      "business_name": "Rounded Development",
      "city": "",
      "created_at": "2012-04-22T18:07:44Z",
      "first_name": "Brian",
      "id": 1,
      "industry": "Entertainment",
      "last_name": "Weinreich",
      "lat": null
    },
    {
      "access_token": null,
      "bio": null,
      "business_name": null,
      "city": null,
      "created_at": "2012-04-23T13:56:35Z",
      "email": "test@jambo.com",
      "first_name": "asdad",
      "id": 2,
      "industry": null,
      "last_name": "ddfs",
      "lat": null,
      "linkedin_id": null,
      "linkedin_url": null,
      "lng": null,
      "position": null,
      "professional_headline": null,
      "state": null,
      "street": null,
      "updated_at": "2012-04-23T13:56:35Z"
    },
    {
      "access_token": null,
      "bio": null,
      "business_name": null,
      "city": null,
      "created_at": "2012-04-23T13:56:39Z",
      "email": "tesasdat@jambo.com",
      "first_name": "fdsd",
      "id": 3,
      "industry": null,
      "last_name": "asdgw",
      "lat": null,
      "linkedin_id": null,
      "linkedin_url": null,
      "lng": null,
      "position": null,
      "professional_headline": null,
      "state": null,
      "street": null,
      "updated_at": "2012-04-23T13:56:39Z"
    },
    {
      "access_token": null,
      "bio": null,
      "business_name": null,
      "city": null,
      "created_at": "2012-04-23T13:56:44Z",
      "email": "asdsad@jambo.com",
      "first_name": "ewtrwef",
      "id": 4,
      "industry": null,
      "last_name": "dfd",
      "lat": null,
      "linkedin_id": null,
      "linkedin_url": null,
      "lng": null,
      "position": null,
      "professional_headline": null,
      "state": null,
      "street": null,
      "updated_at": "2012-04-23T13:56:44Z"
    }
  ]
]

要仅提取ID,您可以执行以下操作:

the_IDs = array_of_hashes.collect { |single_array| single_array["id"] }

显然,您可以使用较少的冗长的变量名,它们只是用于说明。 但想法是,您可以遍历数组并收集块返回的任何内容。 在这种情况下,您将不断返回ID, the_IDs将只是所收集内容的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM