Modifying built-in classes

Inheritance is a powerful idea in object oriented programming. This lets you add new enhancements to existing classes. Well, not exactly. You have to create a new data type derived from the existing classes and use these for additional enhancements.

For example, if we want to add a function palindrome to String class. Solution existing in all (most?) object oriented programming languages is to create a class say Word derived from String and add the function to this class. In Ruby for example it would look like:

Note – replace ‘LT’ with corresponding symbol for less than. HTML is messing it up and I feeling lazy to find the &; version for it.

class Word 'LT' String 
def palindrome? 
   self == self.reverse 
irb> w ="level")
irb> w.palindrome? 
irb> w1 ="simple")
irb> w1.palindrome? 

What we lose here is that we CANNOT call the function on String objects e.g., following is invalid:

irb> "level".palindrome? 
NoMethodError: undefined method `palindrome?' for "level":String

Ruby, quite surprisingly (and did i mention it never fails to amaze!) provides this. It lets you modify the built-in classes. So we can add a function simply by following:

class String 
def palindrome? 
   self == self.reverse 

and it gets your String more powerful!

irb> "level".palindrome? 

Isn’t that coooooool??


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s