【问题标题】:How to merge hashes inside array?如何合并数组内的哈希?
【发布时间】:2019-06-06 06:57:48
【问题描述】:

如何合并这些数组中的哈希:

description = [
  { description: "Lightweight, interpreted, object-oriented language ..." },
  { description: "Powerful collaboration, review, and code management ..." }
]

title = [
  { title: "JavaScript" },
  { title: "GitHub" }
]

所以我明白了:

[
  {
    description: "Lightweight, interpreted, object-oriented language ...",
    title: "JavaScript"
  },
  {
    description: "Powerful collaboration, review, and code management ...",
    title: "GitHub"
  }
]

【问题讨论】:

    标签: ruby ruby-hash


    【解决方案1】:

    如果 1) 只有 2 个要合并的列表,2) 您确定列表的长度相同,并且 3) 列表 l1 的第 n 项必须与 l2 的第 n 项合并(例如项目在两个列表中都正确排序)这可以简单地完成

    l1.zip(l2).map { |a,b| a.merge(b) }
    

    【讨论】:

    • 术语“数组”会更合适。关于 1) – zipmerge 都可以处理多个参数,例如l1.zip(l2, l3).map { |a, b, c| a.merge(b, c) }
    • 没错,每个列表都有相同的长度,但我有两个以上的列表。 @Rajagopalan 的答案很好,两个列表与标题和描述相匹配。现在我正在尝试多个列表。如果您有任何建议请评论。谢谢
    【解决方案2】:

    编写如下代码

    firstArray=[{:description=>"\nLightweight, interpreted, object-oriented language with first-class functions\n"}, {:description=>"\nPowerful collaboration, review, and code management for open source and private development projects\n"}]
    
    secondArray=[{:title=>"JavaScript"}, {:title=>"GitHub"}]
    
    result=firstArray.map do |v|
      v1=secondArray.shift
      v.merge(v1)
    end
    
    p result
    

    结果

    [{:description=>"\nLightweight, interpreted, object-oriented language with first-class functions\n", :title=>"JavaScript"}, {:description=>"\nPowerful collaboration, review, and code management for open source and private development projects\n", :title=>"GitHub"}]
    

    【讨论】:

    • shift 将修改第二个数组。
    【解决方案3】:
    description = [
      { description: "Lightweight, interpreted" },
      { description: "Powerful collaboration" }
    ]
    
    title = [
      { title: "JavaScript" },
      { title: "GitHub" }
    ]
    

    description.each_index.map { |i| description[i].merge(title[i]) }
      #=> [{:description=>"Lightweight, interpreted",
      #     :title=>"JavaScript"},
      #    {:description=>"Powerful collaboration",
      #     :title=>"GitHub"}]
    

    使用zip 时,会构造临时数组description.zip(title)。相比之下,上述方法不创建中间数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2015-05-31
      相关资源
      最近更新 更多