From: matthew@... Date: 2016-09-19T03:00:35+00:00 Subject: [ruby-core:77308] [Ruby trunk Feature#12770] Hash#left_merge Issue #12770 has been updated by Matthew Kerwin. Robert A. Heiler wrote: > I think that the name appears to be a bit strange - if we have a left_merge, do we have a right_merge, an up_merge, a bottom_merge? :) Given that it comes from SQL's [JOIN](https://en.wikipedia.org/wiki/Join_(SQL)) then theoretically, yes, we could have a #right_merge. The directionality in the name implies which of the two "operands" is "more important" -- left_merge means that the rule for resolving collisions is: "keep the value from the left hash when it exists", "right_merge" would presumably be "use the value from the right hash when it exists." i.e. ~~~ruby class Hash def left_merge hsh merge(hsh) {|key, left, right| left.nil? ? right : left } end #def right_merge hsh # merge(hsh) {|key, left, right| right.nil? ? left : right } #end end ~~~ That said, I've never wanted for this functionality to exist in the core. I don't do much of this sort of data mashing in Ruby, though. ---------------------------------------- Feature #12770: Hash#left_merge https://bugs.ruby-lang.org/issues/12770#change-60547 * 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: