Project

General

Profile

Actions

Feature #19148

open

Define Hash#merge_sum as Hash#merge with sum block

Added by hgraham (Harry Graham) almost 2 years ago. Updated almost 2 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:110880]

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

Also available in: Atom PDF

Like0
Like0