Monkey Patching in Ruby

suggest change

Remarks

Monkey patching, while convenient, has some pitfalls that aren’t immediately obvious. Most notably, a patch like that in the example pollutes the global scope. If two modules both add Hash#symbolize, only the last module required actually applies its change; the rest are erased.

If a patched method raises, the backtrace points at the patched class, so it looks like a bug in Hash itself.

Ruby containers can hold mixed objects. A method that looks straightforward for numbers breaks on other objects. Array#sum (added in Ruby 2.4) adds with +. An array of a custom class works only if those objects implement +.

A safer alternative is refinements, available in Ruby >= 2.0.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents