Changing a class later on - Ruby
Archive - Originally posted on "The Horse's Mouth" - 2011-02-02 17:55:19 - Graham EllisIn Ruby, you can define a class ... and then come back and add methods to it. But why would you want to?
Let's suppose that you've got a base class - I'll use "Rectangle" as my example, and you've already subclassed it to "Square" and perhaps a few other things, via a required file that you share between a number of programs. Then you want to use that group of classes in a new application, but with a modification to one of the base methods. The example I used during yesterday's course was that the rectangles were pictures, and I wanted to add a frame, 1 unit wide, around them in my new code. [full source].
Well - given that scenario, you've got an excellent excuse for going back within your own code and replacing the methods of Rectangle that are changed when you add a frame, and it'll be the new routines that are run when you call methods in the already-defined subclasses. It's very neat indeed, and the alternative would be ugly.