From: "hgraham (Harry Graham)" Date: 2022-11-24T15:54:05+00:00 Subject: [ruby-core:110880] [Ruby master Feature#19148] Define Hash#merge_sum as Hash#merge with sum block Issue #19148 has been reported by hgraham (Harry Graham). ---------------------------------------- Feature #19148: Define Hash#merge_sum as Hash#merge with sum block https://bugs.ruby-lang.org/issues/19148 * Author: hgraham (Harry Graham) * Status: Open * Priority: Normal ---------------------------------------- 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: ```ruby 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: ```ruby 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: * https://stackoverflow.com/a/56190912 * https://stackoverflow.com/a/4453690 * https://codereview.stackexchange.com/a/136546 * https://www.appsloveworld.com/ruby/100/242/ruby-merge-sum-values-from-two-distincts-objects-having-the-same-keys -- https://bugs.ruby-lang.org/ Unsubscribe: