Issue #12770 has been updated by Derek Kniffin.


Ah, yep, here's a better example:

````ruby
a = {a: 1, b: nil, c: 3, d: nil}
b = {a: 1, b: 2, c: 4, e:nil}
a.left_merge(b) # => {a: 1, b: 2, c: 3, d: nil}
````

And yea, I admit it's not a great name. The reason I chose left_merge is because it's like a left join in SQL. I'm up for suggestions on improving it.

As for lack of need, that might be true, but I was surprised to see this wasn't a method. I mostly made this feature to propose the idea, and see how many other people would be interested in it.

----------------------------------------
Feature #12770: Hash#left_merge
https://bugs.ruby-lang.org/issues/12770#change-60535

* Author: Derek Kniffin
* Status: Open
* Priority: Normal
* Assignee: Yukihiro Matsumoto
----------------------------------------
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:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>