Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 合并两个散列中的数据_Ruby_Hash_Merge - Fatal编程技术网

Ruby 合并两个散列中的数据

Ruby 合并两个散列中的数据,ruby,hash,merge,Ruby,Hash,Merge,我想合并以下两个哈希数组(arr1和arr2)。最好的方法是什么 要对键的值进行聚合:\u id arr1 = [ { "_id": { "year": 2017, "month": 3 }, "enroll_count": 2267 }, { "_id": { "year": 2017, "month": 2 }, "enroll_count": 1829 } ] arr2 = [

我想合并以下两个哈希数组(
arr1
arr2
)。最好的方法是什么

要对键的值进行聚合
:\u 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
,但没有成功

(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
  #                              }
  #   } 
这使用了(aka
merge!
)的形式,该形式使用块(
{u124;,o,n | o.merge(n)}
)来确定合并的两个哈希中存在的键(
:\u id
)的值。有关该值解析块中三个块变量值的说明,请参见文档

此方法不需要将散列组合在各自的数组中以具有相同的索引