From: Eric Mahurin Date: 2007-06-26T01:35:34+09:00 Subject: using closures as a replacement for "class", @, and @@ Some of you might find it interesting that ruby's closures/blocks can be used as an alternative for defining classes/objects. It's actually quite simple. You just do this: - instead of class/def initialize, you use a function/method to define how to create/initialize an object of that "class" (the function name). - add methods by calling define_method w/ a block on the metaclass on the object that the "class" function will return. - local variables of the "class" function become "instance" variables since all of the blocks used for defining methods are closures and have access to them. - a variable outside that "class" function that is accessible can be used a "class variable". - inheritance is easily done by starting with an object of the base class - multiple inheritance is probably best done with using a "has-a" relationship and delegating particular methods to particular member objects. You could also mixin using Object#extend. - calling a base class method can be done several ways: a) renaming the base method before redefining the derived method, b) store the base method in an instance variable, c) use a "has-a" relationship and store the base object in an instance variable - inherit/delegate or define each method explicitly. All this is mostly academic. You should be able to base a complete object-oriented language on closures. There are a few advantages: - don't need keywords for classes: class, module, self, super, etc. - don't need to prefix instance/class variable with @ and @@. It is determined by closure scope instead. - don't need a special "initialize" method. You put this functionality at the top-level of the "class" definition instead. - instance variables are completely private. You could even have base and derived classes with instance variables of the same name and they won't collide. Of course you might consider this a disadvantage when you want a derived class to access an instance variable of a base class, but this can be done by providing methods to the instance variables. Here is a simple example: class Object # are we ever going to get the fundamental method built-in to Object? def metaclass class<