Serg Ra6n
Serg Ra6n

Reputation: 93

How do I create a custom "merge" method for hashes?

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

Answers (2)

sawa
sawa

Reputation: 168219

class Hash
  def custom_merge other
    merge(other){|_, *a| a}
  end
end

Upvotes: 0

Arup Rakshit
Arup Rakshit

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

Related Questions