如何合并数组中的哈希值?

How to merge hashes inside array?

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

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

编写如下代码

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

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

一样简单地完成
l1.zip(l2).map { |a,b| a.merge(b) }
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) 被构建。相比之下,上面的方法没有创建中间数组。