Merging two hashes

I am using the Google Civic Information API. This gives me two hash arrays. I want to print information from the screen. Hash 1 has some integers as a pair of kv (officialIndices). They represent the index number for the corresponding object in the second hash. How can these two be combined? I want to display information from both hashes together. It might be better to replace the official index values ​​with an 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 the hash array. Hash 2 is the first hash in the hash array. I would like to replace the number in officialIndice in Hash 1 with Hash 2. This is confusing because some official indexes have more than one number. Hope this makes sense.

+4
3

; , officialIndices ?

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

(: , .. array1. , array1 , .)

+2

Hash#merge :

foo = { "name" => "President of the United States" }
bar = { "name" => "Barack Obama" }

foo.merge(bar) { |key, old_val, new_val| {description: old_val, value: new_val} }
=> {"name"=>{:description=>"President of the United States", 
             :value=>"Barack Obama"}}

, merge . , .

+2

You can use Hash#mergeto combine information from two hashes. However, you have an overlapping key ( name) in both cases, so you'll want to rename it with either a hash before merging:

# Rename "name" to "position_name" before merging to prevent collision
hash1["position_name"] = hash1.delete("name")

merged_hash = hash1.merge(hash2)
+1
source

All Articles