rodrigosaito.com

home

Ruby open classes

12 Sep 2012

Sometimes is very useful to add methods to ruby classes that are not on your code base.

Let's say you have an utility class with an utility methods called sub_comma_by_space that substitute all commas on a String by spaces:

1 def self.sub_comma_by_space(str)
2   str.sub ",", " "
3 end

This could be more object oriented if we can use this method like this:

1 "Test,string".sub_comma_by_space

In Java, for example, you would have to create a new "PowerString" with all String methods and add this method to your "PowerString" and then change all your references to use your new "PowerString" instead of String class.

Ruby has the concept of open classes so you can easily extend an existing ruby class, without changing the String source file:

1 class String
2   def sub_comma_by_space
3     sub ",", " "
4   end
5 end

Now you can call sub_comma_by_space method on all you Strings.