Monkey Patching in Ruby
suggest changeRemarks
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents