Overriding Constructors in Ruby (or: A better Bitmap class in RPGXP)

Tue, 17 Jul 2007 17:46:00 +0000 - Author: Peter O.

A little known fact about the Ruby language is that the New method of each object calls the "initialize" method to instantiate the object. Even though limitations of the language prevent class methods from being replaced using alias (thus preventing something like "Alias oldnewmethod Bitmap.new"), it is still possible to override the "initialize" method, or the constructor in more familiar terms.

An example comes from RPG Maker XP's RGSS system:

class Bitmap
alias originalInitialize initialize

def initialize(*arg)
 if arg.length==1
   print("#{arg[0]}")
 else
   print("#{arg[0]} #{arg[1]}")   
 end 
 return originalInitialize(*arg)
end

end

This short sample prints the parameters passed to any Bitmap.new call in the program. Possibilities with this technique including supporting more file formats (RGSS's built-in Bitmap class supports PNG and JPEG files), faster implementation of the integrated methods (such as set_pixel and get_pixel), and potentially others.


Discussion

Other Formats