合并来自两个哈希的数据

时间:2017-03-23 03:48:59

标签: ruby hash merge

我想合并以下两个哈希数组(arr1arr2)。这样做的最佳方式是什么?

要对密钥:_id的值进行聚合。

arr1 = [
  {
    "_id": {
      "year": 2017,
      "month": 3
    },
    "enroll_count": 2267
  },
  {
    "_id": {
      "year": 2017,
      "month": 2
    },
    "enroll_count": 1829
  }
]

arr2 = [
  {
    "_id": {
      "year": 2017,
      "month": 3
    },
    "other_count": 2
  },
  {
    "_id": {
      "year": 2017,
      "month": 2
    },
    "other_count": 3
  }
]

期望的结果

[
  {
    "_id": {
      "year": 2017,
      "month": 3
    },
    "enrolled_count": 2267,
    "other_count": 2
  },
  {
    "_id": {
      "year": 2017,
      "month": 2
    },
    "enrolled_count": 1829
    "other_count": 3
  }
]

我尝试使用Hash#merge,但没有成功。

1 个答案:

答案 0 :(得分:0)

(arr1+arr2).each_with_object({}) {|g,h| h.update(g[:_id]=>g) {|_,o,n| o.merge(n)}}.values
  #=> [{:_id=>{:year=>2017, :month=>3}, :enroll_count=>2267, :other_count=>2},
  #    {:_id=>{:year=>2017, :month=>2}, :enroll_count=>1829, :other_count=>3}] 

请注意,在执行.values之前,我们有

(arr1+arr2).each_with_object({}) {|g,h| h.update(g[:_id]=>g) {|_,o,n| o.merge(n)}}
  #=> {{:year=>2017, :month=>3}=>{:_id=>{:year=>2017, :month=>3},
  #                               :enroll_count=>2267,
  #                               :other_count=>2
  #                              },
  #    {:year=>2017, :month=>2}=>{:_id=>{:year=>2017, :month=>2},
  #                               :enroll_count=>1829,
  #                               :other_count=>3
  #                              }
  #   } 

这使用Hash#update(aka merge!)的形式,它使用块({ |_,o,n| o.merge(n) })来确定两者中存在的键值(:_id)哈希被合并。有关该值解析块中三个块变量值的解释,请参阅doc。

此方法不要求要组合的哈希在各自的数组中具有相同的索引。

相关问题