2012-08-02 63 views
0

我有一個下面的哈希映射的當前數組,我有另一個數組,我想通過匹配的id插入到每個哈希。如何在Ruby中將數組插入到現有的散列數組中?

{"url"=>"http://ubuntu64:1990/getpages", 
    "id"=>"32794", 
    "version"=>"2", 
    "title"=>"Creating a page", 
    "space"=>"test", 
    "parentId"=>"32782", 
    "permissions"=>"0"} 

其他陣列我想添加一個基於ID的 'IMAGEURL' 鍵/值,所以像(如ID == ID插入 'IMAGEURL'/'someurl.jpg}

{"id"=>"32794", "imageurl" => "someurl.jpg} 

回答

2
array = [...] #Declare your array with the "big" hashes here 
array2 = [...] #Declare your array with the hash containing the imageurl key here 

array.each do |a| 
    array2.each do |a2| 
    if a[:id] == a2[:id] 
     a[:imageurl] = a2[:imageurl] 
     break #We found it 
    end 
    end 
end 

應該做的伎倆......也許有一個更聰明的方式做到這一點,雖然

+0

感謝安東尼,這裏是IMAGEURL被添加到大的散列陣列的部分是它?[:IMAGEURL] = a2 [:imageurl]?記住第一個數組沒有'imageur我的鑰匙。 – user979587 2012-08-02 15:02:29

+0

是的[:imageurl]將在'array'數組中包含的哈希值中創建密鑰 – 2012-08-02 15:03:58

+0

farken ruby​​真棒 – user979587 2012-08-02 15:04:49