> From: nosuzuki / e-mail.ne.jp [mailto:nosuzuki / e-mail.ne.jp]On Behalf Of > Johann Hibschman [..] > Hi, > > Could someone either explain singleton classes to me or point me to a > good explanation? The one from the Ruby reference manual just > confuses. Where are these things useful and what, precisely, are > their semantics? > > I've used them once, so far, when I wanted to effectively add a method > to class Class that only applied to one of my classes. I did this to > implement a little abbreviation for defining methods within my class. > > Is there a canonical usage for these things, or was what I did it? Hi, I like to think of Singletons the following way: Each Ruby object comes with a type (in Class) and its ``singleton_type'' (its ``id'' in Fixnum) (note the analogy breaks down for Fixnums but you can't define a singleton method for Fixnums anyway). You can recover the type from the ``singleton_type'' with the following script (untested of course;-) but not the other way around. ------------- class Object alias :singleton_type :id end SingletonType = Fixnum Type = Class class SingletonType def to_type ObjectSpace.each_object(Class) do |klass| ObjectSpace.each_object (klass) do |obj| return klass if self == obj.id end end raise "no type associated" end end class A end x = Object.new y = A.new z = 23 p x.singleton_type.to_type # => Object p y.singleton_type.to_type # => A p z.to_type # raises an exception ----------- It is amusing to speculate about an extensions in the other direction. For example a method ``meth'' which is bound to a pair of types A,B (you probably want to replace self with self_left, self_right and rename ``singleton method'' to ``individualton method'') could be called ``dualton method''. Hypothetical you could call a ``dualton-method'' with syntax like {a,b}.meth (arg) where a,b are objects of type A,B. [...] Christoph