Reputation: 93
How do I implement a "custom_merge" method?
h1 = {a: 1, c: 2}
h2 = {a: 3, b: 5}
This is a standard "merge" method implementation:
h1.merge(h2) # => {:a=>3, :c=>2, :b=>5}
My desired "custom_merge" method should implement:
h1.custom_merge(h2) # {a: [1, 3], b: 5, c: 2}
Upvotes: 3
Views: 523
Reputation: 118289
No need the custom_merge method. Ruby core supplied Hash#merge
with block will help you out.
h1 = {a: 1, c: 2}
h2 = {a: 3, b: 5}
h3 = h1.merge(h2){|k,o,n| [o,n]}
h3
# => {:a=>[1, 3], :c=>2, :b=>5}
Upvotes: 6