Monkey Patching in Ruby

If you, or someone you know is involved with the development of web applications, chances are that you’ve heard of Ruby on Rails. I’ve recently decided to use it for a few small projects and am simply amazed at how spectacular it is. In case you don’t know, Rails is a framework written in the Ruby programming language, for developing web applications. If that doesn’t make much sense to you, then you should probably stop reading now.

There have been other web frameworks in other programming languages that closely emulate Rails, but think a lot of the magic comes from Ruby itself.

One of the things about Ruby that I recently learned was how you can ‘re-open’ a defined class ( supposedly referred to as ‘monkey patching‘ or ‘duck punching’ )

If you had the following class defined:

class Thing
 def foo
 puts 'foo!'
 end
end

You could, later on add a method to this class, at runtime:

class Thing
 def bar
 puts 'bar!'
 end
end

The interpreter will add the ‘bar’ method to the class without error or warning. This can also be applied to Ruby’s internal base classes, the following code for example adds a method named rot13 to the String class

class String
 def rot13
 self.tr! 'A-Za-z', 'N-ZA-Mn-za-m'
 end
end

puts 'Hello world!'.rot13
=> 'Uryyb Jbeyq!'

I think this is one of the reasons why Rails plug-ins to integrate so well

This would have saved me a ton of work if PHP was able to do this.