合并两个哈希

时间:2016-05-07 23:15:48

标签: ruby-on-rails ruby api hash

我正在使用Google思域信息API。它给了我两个哈希数组。我想在屏幕上打印两者的信息。散列1有一些整数作为k-v对(officialIndices)。这些表示第二个哈希中相应对象的索引号。如何合并这两个?我想一起显示两个哈希的信息。也许最好用第二个数组中的索引哈希替换officialIndices的值。谢谢你的建议!

哈希1:

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

哈希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" }
  ]
}

编辑**为了澄清,哈希1是哈希数组中的第一个哈希。散列2是散列数组中的第一个散列。我想用Hash 2替换Hash 1中的officialIndice中的数字。这让我感到困惑,因为一些官方指标有多个数字。希望有道理。

3 个答案:

答案 0 :(得分: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逻辑。如果您有多个具有相似逻辑的重叠键,则此解决方案有效。

答案 1 :(得分:2)

合并不起作用;如果function createAnObject(name, address) { var newObj = new Object(); newObj.name = name; newObj.address = address; newObj.saySomething = function () { console.log("the name is" + this.name + " the addess is" + this.address) } return newObj; }; var ballack = createAnObject('ballack', 'Ndri'); console.log(ballack.name); // Now outputs 'ballack' 有多个元素,你会怎么做?

officialIndices

(注意:这是破坏性的,即它会改变array1.each do |el1| el1["officials"] = el1["officialIndices"].map { |idx| array2[idx] } el1.delete("officialIndices") end 。如果你希望array1不变,我会重写。)

答案 2 :(得分:1)

您可以使用Hash#merge合并来自两个哈希的信息。但是,两者都有一个重叠键(name),因此您需要在合并之前将其重命名为哈希:

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

merged_hash = hash1.merge(hash2)