如何在数组中合并哈希



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

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

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

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

编写以下代码

firstArray=[{:description=>"nLightweight, interpreted, object-oriented language with first-class functionsn"}, {:description=>"nPowerful collaboration, review, and code management for open source and private development projectsn"}]
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 functionsn", :title=>"JavaScript"}, {:description=>"nPowerful collaboration, review, and code management for open source and private development projectsn", :title=>"GitHub"}]
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)。相比之下,上述方法不会创建中间数组。

最新更新