如何合并这些数组中的哈希:
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"
}
]
答案 0 :(得分:3)
如果1)仅合并两个列表,2)您确定列表长度相同,并且3)必须将列表l1
的第n个项目与{{1}的第n个项目合并}(例如,两个列表中的项目均已正确排序),只需完成
l2
答案 1 :(得分: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"}]
答案 2 :(得分: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)
。相比之下,上述方法不创建任何中间数组。