Actions
Feature #19148
openDefine Hash#merge_sum as Hash#merge with sum block
Status:
Open
Assignee:
-
Target version:
-
Description
To merge two hashes whilst summing any common elements, we currently have to pass a block instructing how to add the elements from each hash:
items_1_counts = {:book => 4, :pen => 2, :pencil => 3}
items_2_counts = {:book => 2, :pencil => 6, :rubber => 11}
items_1_counts.merge(items_2_counts) { |_k, a, b| a + b }
=> {:book => 6, :pen => 2, :pencil => 9, :rubber => 11}
Having a method for this would (in my opinion) simplify it:
items_1_counts.merge_sum(items_2_counts)
=> { :book => 6, :pen => 2, :pencil => 9, :rubber => 11 }
Would this benefit many people?¶
This (merging two hashes whilst summing any common elements) seems to be a common scenario that many people raise on forums:
Actions
Like0
Like0