如何在Ruby中将数组插入现有的哈希数组?

时间:2012-08-02 14:52:07

标签: ruby-on-rails ruby

我有一个下面哈希映射的当前数组,我有另一个数组,我希望通过匹配id在每个哈希中插入。

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

另一个数组我想根据id添加'imageurl'键/值,所以像(如果id == id insert'mageurl'/'someurl.jpg}

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

1 个答案:

答案 0 :(得分: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

应该做的伎俩...也许有一种更聪明的方法来做到这一点