What is Monkey-Patching?
As you read about Ruby you’ll often see the term “monkey patching”. It’s used all over the place by experienced Rubyists but it’s one of those dangerous things that is very easy to misuse or abuse.
So if you’re confused about what it is, here’s a quick explanation:
Ruby is an extremely dynamic language. That means that you can do things to existing classes at run-time that other languages and environments do not allow.
And that’s what monkey-patching is all about.
Suppose you’re working with Strings — and your linguist friend has designed an algorithm that can tell if a particular phrase is written in French.
Wouldn’t it be great if you could do something like this:
“Je m’appelle Helene”.is_french? => true
“My name is Claire”.is_french? => false
In most languages that would not be possible — String is a system class and it’s methods are pre-defined.
But not in Ruby.
We can “reopen” the String class, define our new is_french? method et voila, our String class is now francophile-aware.
# complicated linguistic analysis code goes here
When Ruby finds this code it knows that String is already defined, so instead of creating a new class, it just adds the is_french? method to the existing String class.
And there you have it — monkey-patching in action. Extremely dangerous, because you can redefine the behaviour of any class in your system, but also incredibly powerful, making it simple to do things that are extremely long-winded in other development environments.