On 2005.12.11 10:34, "jonathan <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu>" <zjll9 / imail.etsu.edu> wrote: > dblack wrote: > >> Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses > >> that aren't singletons and extend them as well as instanciate instances > >> of them, right? That would provide the flexibility I was referring to > >> above, but I suppose it would require typing quite a few more > >> characters. So do I understand correctly that Matz designed the whole > >> singleton creation mechanism ( << ) as a shorthand for doing more > >> long-winded dynamic creation/enhancing? > > > > The starting-point of the whole thing is the principle that objects > > can be individually extended. Two instances of MyClass, for example, > > begin life with the same capabilities (methods), but during their > > lives can diverge: > > > > class MyClass > > end > > > > a = MyClass.new > > b = MyClass.new > > > > def a.x > > end > > > > def b.y > > end > > > > The singleton class mechanism is just a way to store those "extra" > > methods. The methods written for a (namely, "x") go in a's singleton > > class; those for b, in b's; etc. These classes are created > > automatically when they are needed. > > Hmm. Ok, so there really is no singleton class for Myclass? In other > words, must the singleton always be associated with an instance and not > a class? > > > > > If you want to open a class definition block for an object's singleton > > class, you use the class keyword, plus "<< obj". This special syntax > > is necessary because singleton classes are anonymous. Other than > > that, it's very much like doing "class C". > > > > It's all very simple and elegant, isn't it? :-) > > > > Yea. That is cool, but can you still do something like this: > > class Myclass > end > > def extend_class( some_class ) > code = %{ class #{some_class.class}_extension < #{some_class.class} > def new_method1 > end > ... > end } > eval( code ) > > extend_class( Myclass ) > x = Myclass_extension.new > x.new_method1 > y = Myclass_extension.new > y.new_method1 > > Some variation of this (where the extended class is named uniquely) > should allow infinitely many extended subclasses and also allow > non-singleton (i.e., many) instances of the subclasses. Typically, if I understand you correctly, you could just use this idiom (unless you want to just eval the whole thing): # Classes are constants # | Inherit MyClass # | | We can use blocks # | | | # V V V MyClassExtension = Class.new(MyClass) { def self.some_method() # ... end def some_method() # ... end } > Of course, I suppose you could start with x and y as instances of the > base class and add the new_method's to each of them just as easily (and > with probably less typing). So, would there ever be a reason to do > something like I wrote above? > > --J E