-1

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

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

3 回答 3

3

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

l1.zip(l2).map { |a,b| a.merge(b) }
于 2019-06-06T07:08:50.253 回答
0

编写以下代码

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"}]
于 2019-06-06T07:05:04.007 回答
0
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)构造。相比之下,上述方法不创建中间数组。

于 2019-06-06T07:58:55.747 回答