-1

How do I merge the hashes in these arrays:

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

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

so I get:

[
  {
    description: "Lightweight, interpreted, object-oriented language ...",
    title: "JavaScript"
  },
  {
    description: "Powerful collaboration, review, and code management ...",
    title: "GitHub"
  }
]
Stefan
  • 109,145
  • 14
  • 143
  • 218
Ganesh Raju
  • 95
  • 1
  • 14

3 Answers3

3

If 1) thare are only 2 lists to merge, 2) you're sure the lists are of the same length and 3) nth item of list l1 must be merged with nth item of l2 (e.g. items are properly ordered in both lists) this can be done as simple as

l1.zip(l2).map { |a,b| a.merge(b) }
Konstantin Strukov
  • 2,899
  • 1
  • 10
  • 14
  • 2
    The term "array" would be more appropriate. Regarding 1) – `zip` and `merge` can both handle multiple arguments, e.g. `l1.zip(l2, l3).map { |a, b, c| a.merge(b, c) }` – Stefan Jun 06 '19 at 07:16
  • exactly, every list has same length but i have more than two lists. The answer from @Rajagopalan is just fine two lists are matching with title and description. Now I am trying for multiple lists. If you have any suggestion plz comment. Thank you – Ganesh Raju Jun 06 '19 at 07:19
0

Write the following code

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

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"}]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
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"}]

When using zip the temporary array description.zip(title) is constructed. By contrast, the method above creates no intermediate array.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100