【问题标题】:Merging Two Hashses合并两个哈希
【发布时间】:2016-09-02 20:10:06
【问题描述】:

我正在使用 Google Civic Information API。它给了我两个哈希数组。我想在屏幕上打印两者的信息。哈希 1 有一些整数作为 k-v 对(官方索引)。这些表示第二个哈希中相应对象的索引号。这两个怎么合并?我想同时显示来自两个哈希的信息。也许用第二个数组中的索引哈希替换 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 中的数字。这让我很困惑,因为一些 officialIndice 有多个数字。希望这是有道理的。

【问题讨论】:

  • 你说,“这些代表第二个哈希中对应对象的索引号。”什么是“对应对象”?该索引如何用于构建合并的哈希?请编辑以澄清并显示您的示例所需的合并哈希。

标签: ruby-on-rails ruby api hash


【解决方案1】:

合并不起作用;如果officialIndices 有多个元素,你会怎么做?

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

(注意:这是破坏性的,即它会改变array1。如果你想要array1不变,我会重写。)

【讨论】:

  • 我建议el1["officials"] = array2.values_at(*el1["officialIndices"])。你已经擅离职守了。
【解决方案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 个具有相似逻辑的重叠键,则此解决方案有效。

【讨论】:

  • 谢谢。那是真的,但我并不完全清楚。哈希 1 是哈希数组中的第一个哈希。哈希 2 是哈希数组中的第一个哈希。我只想结合这两个哈希的信息。我可以通过使用 officialIndice 并将其插入第二个数组来做到这一点。 officialIndice 表示第二个哈希的索引号。
【解决方案3】:

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

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

merged_hash = hash1.merge(hash2)

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2016-10-07
    • 2018-10-31
    • 1970-01-01
    • 2017-12-18
    • 2020-09-25
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多