Ruby : check whether method is monkey patched or not

01 Dec 2012


Consider a situation that one of the ruby method is acting weird, means not delivering the expected functionality. So you doubt that some of the gem is monkey patched that method. How you are going to find the monkey patch?

Here is the simple solution to make sure that the method is not monkey patched, or get the file and line number where the method is patched.

The trick works with the help of source_location method. This method will return the file path and line number of the method or nil if the method is native.


In the above sample I tried to monkey patch the split method of String class. In line number 2 you can see that the source_location method returns "nil" since the method is not patched. But in line number 5 you can see that the source_location method returns an array of two elements, first is the file path, in this case it is pry/irb,  second one is the line number.

Here is the snippet I used in the above example. You can fork and try to execute it.


Hope this will save your time.
Thank you.
If you find my work helpful, You can buy me a coffee.