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
# }
# }
这使用了(akamerge!
)的形式,该形式使用块({u124;,o,n | o.merge(n)}
)来确定合并的两个哈希中存在的键(:\u id
)的值。有关该值解析块中三个块变量值的说明,请参见文档
此方法不需要将散列组合在各自的数组中以具有相同的索引