Colin R. Colin R. - 6 months ago 20
Ruby Question

Merging Two Hashses

I am using the Google Civic Information API. It is giving me two arrays of hashes. I want to print information from both on the screen. Hash 1 has some integers as a k-v pair (officialIndices). These represent the index number for the corresponding object in the second hash. How can merge these two? I want to display the information from both hashes together. Maybe it would be better to replace the values of officialIndices with the indexed hash in the second array. Thanks for any advice!

Hash 1:

{
"name" => "President of the United States",
"divisionId" => "ocd-division/country:us",
"levels" => ["country"],
"roles" => ["headOfState", "headOfGovernment"],
"officialIndices" => [0]
}


Hash 2:

{
"name" => "Barack Obama",
"address" => [{
"line1" => "The White House",
"line2" => "1600 pennsylvania avenue nw",
"city" => "washington",
"state" => "DC",
"zip" => "20500"
}],
"party" => "Democratic",
"phones" => ["(202) 456-1111"],
"urls" => ["http://www.whitehouse.gov/"],
"photoUrl" => "http://www.whitehouse.gov/sites/default/files/imagecache/admin_official_lowres/administration-official/ao_image/president_official_portrait_hires.jpg",
"channels" => [
{ "type" => "GooglePlus", "id" => "+whitehouse" },
{ "type" => "Facebook", "id" => "whitehouse" },
{ "type" => "Twitter", "id" => "whitehouse" },
{ "type" => "YouTube", "id" => "barackobama" }
]
}


EDIT** To clarify, Hash 1 is the first hash in an array of hashes. Hash 2 is the first hash in an array of hashes. I would like to replace the number in officialIndice in Hash 1 with Hash 2. It's confusing me because some officialIndices have more than one number. Hope that makes sense.

Answer

Merge won't work; what will you do if officialIndices has multiple elements?

array1.each do |el1|
  el1["officials"] = el1["officialIndices"].map { |idx|
    array2[idx]
  }
  el1.delete("officialIndices")
end

(Note: this is destructive, i.e. it will change array1. If you want array1 unchanged, I'll rewrite.)

Comments