【问题标题】:Merge Data from two hashes合并来自两个哈希的数据
【发布时间】:2017-08-15 11:15:00
【问题描述】:

我想合并以下两个哈希数组(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,但没有成功。

【问题讨论】:

    标签: ruby hash merge


    【解决方案1】:
    (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(又名merge!)的形式,它使用一个块({ |_,o,n| o.merge(n) })来确定在被合并的两个哈希中都存在的键的值(:_id)。有关该值解析块中三个块变量的值的说明,请参阅文档。

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

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 2016-10-07
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2011-04-23
      相关资源
      最近更新 更多