2012-04-23 55 views
0

我有一個散列數組(或至少我認爲它們是散列),我需要爲它們中的每個散列ID。我確信紅寶石有一些快速的方法來做到這一點......我只是無法弄清楚。我不想迭代數組並創建一個新的數組。如何從紅寶石中的哈希數組中獲取鍵/值對?

[ 
    [ 
    { 
     "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": "[email protected]", 
     "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": "[email protected]", 
     "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": "[email protected]", 
     "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" 
    } 
    ] 
] 
+1

你需要修正你的哈希值:'=>',而不是':'和'nil'而不是'null',即它應該看起來像這樣:''lat'=> nil'。在這個例子中你也有一個太多的數組。除非你真的使用散列數組。 – TsukinoMai 2012-04-23 15:55:55

+2

@TsukinoMai我認爲OP實際上發佈了JSON,而不是Ruby。否則,是的,你應該在散列應該如何使用'=>'而不是':'來正確。 – MrDanA 2012-04-23 16:09:08

+1

@MrDanA那麼,如果他想使用ruby方法來獲取信息,他需要將它變成紅寶石哈希。在目前的狀態下,你的解決方案(或任何其他方面)只會給他帶來錯誤。 – TsukinoMai 2012-04-23 16:23:16

回答

1

拉出來只不過是你能做到這一點的ID:

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

很明顯,你可以用更少的冗長的變量名,他們只是爲了說明。但是,這個想法是,你可以遍歷一個數組並收集塊返回的內容。在這種情況下,您不斷收到返回的ID,並且the_IDs只是收集的數組。

+0

謝謝!只是我在找什麼。 – 2012-04-23 16:40:02