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.

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.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe