Ruby Open Classes

In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever's there.

Now to the program p031motorcycletest.rb in the last topic, add the method dispAttr

Please note that self.class refers to Object and self refers to an object called main of class Object.

One more example is program - p031xdognext.rb

Here's another example of adding a method to the String class.

We would like to add a write_size method to the String class. But first, we shall get a list of all methods in Ruby's standard String class that begins with wr:

We observe that the String class has no method starting with wr. Now let's write the program p032mystring.rb:

(You can confirm the output to the above programs yourself).

If you're writing a new method that conceptually belongs in the original class, you can reopen the class and append your method to the class definition. You should only do this if your method is generally useful, and you're sure it won't conflict with a method defined by some library you include in the future. If your method isn't generally useful, or you don't want to take the risk of modifying a class after its initial creation, create a subclass of the original class. The subclass can override its parent's methods, or add new ones. This is safer because the original class, and any code that depended on it, is unaffected.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on and in the course at is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.