Search code examples
rubyruby-hash

How to merge hashes inside array?


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

Solution

  • 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) }