Monkey Patching in Ruby

Yahya Gok
2 min readMay 17, 2021

Ruby has the ability to re-open any class and change it’s methods. We can reopen any class and change how it works. This includes the standard Ruby classes like String, Array or Hash!. That is called monkey patching. Monkey patch would not change the software itself, but only the local copy while it’s being run.

Every class in Ruby has its own list of built-in methods. For example, a string has a whole list of methods: including #reverse which will reverse the order of the string, #count which will count how many characters are in the string, #empty? which will tell you whether the string is empty or not by returning true or false.(1)

As you can see below pictures show string and array have a lot of built in methods. For example; let’s say that this is our array;

array = [1,2,3,4]

array.methods will give us all the methods in irb tab. For example; array.include?, array.push, array.append and so on.

Monkey Patching changes built in method’s way to our way. All those built in methods could be changeable to our way. For example;

As you can see below picture, we have a String class and this string class has reverse method. So what we do here is changing the way how reverse built in method used to work. Like here I’m just saying if I use reverse method to any string. It will give me this puts “You change the way how it work, I can not reverse”. So we basically, rebuilt this built-in method to our new reverse method.

Resources

resource for (1)

--

--