Ruby Language Monkey Patching in Ruby

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.

Furthermore, if there's an error in a patched method, the stacktrace simply points to the patched class. This implies that there's a bug in the Hash class itself (which there is now).

Lastly, because Ruby is very flexible with what containers to hold, a method that seems very straightforward when you write it has lots of undefined functionality. For instance, creating Array#sum is good for an array of numbers, but breaks when given an array of a custom class.

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



Got any Ruby Language Question?