Project

General

Profile

Actions

Feature #12770

closed

Hash#left_merge

Added by dkniffin (Derek Kniffin) over 7 years ago. Updated over 7 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:77295]

Description

I would like a Hash method that does the following:

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:

class Hash
  def left_merge(new_hash)
    merge(new_hash) { |_, old_v, new_v| old_v || new_v }
  end
end
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0