Mauricio
Mauricio

Reputation: 5853

merge hashes using + operator

Do you see any drawback (besides the obvious ones with monkey patching) in doing this?

class Hash
   def +(other)
     self.merge(other)
   end
end

I found this really handy, but maybe there's something I'm not considering and could be problematic.

Upvotes: 2

Views: 137

Answers (1)

sawa
sawa

Reputation: 168081

I don't see any major drawbacks. A very minor drawback is that it adds an extra level to a call stack, making it slightly slower. To avoid this, you can use alias:

class Hash
  alias :+ :merge
end

A benefit may be that you will be able to use the += syntax sugar, but I cannot think of a use case where you want to use += instead of merge!. The difference between them is whether the object id changes.

Upvotes: 3

Related Questions