[ruby-core:77304] [Ruby trunk Feature#12770] Hash#left_merge
From:
derek.kniffin@...
Date:
2016-09-17 19:58:22 UTC
List:
ruby-core #77304
Issue #12770 has been updated by Derek Kniffin.
Ah, hmm. I think new example was a bit off as well. The return value should be:
`{ a: 1, b: 2, c: 3, d: nil, e: nil }`
----------------------------------------
Feature #12770: Hash#left_merge
https://bugs.ruby-lang.org/issues/12770#change-60540
* Author: Derek Kniffin
* Status: Feedback
* Priority: Normal
* Assignee:
----------------------------------------
I would like a Hash method that does the following:
````ruby
a = {a: 1, b: nil, c: nil, d: nil}
b = {a: 1, b: 2, c: nil}
a.left_merge(b) # => {a: 1, b: 2, c: nil, d: nil}
````
So, it takes the first hash, and for any values that are nil, if there's a value for that key in the second hash, fill in the value from the second hash.
I've searched around a bit, and I haven't found this anywhere, so I'd like to propose a new one: `Hash#left_merge`. I've also got a first draft of the method definition:
````ruby
class Hash
def left_merge(new_hash)
merge(new_hash) { |_, old_v, new_v| old_v || new_v }
end
end
````
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>