From: Christoph Rippel Date: 2001-03-04T11:43:11+09:00 Subject: [ruby-talk:11961] RE: singleton classes? > From: nosuzuki@e-mail.ne.jp [mailto:nosuzuki@e-mail.ne.jp]On Behalf Of > Johann Hibschman > Sent: Saturday, March 03, 2001 12:40 PM > To: ruby-talk ML; ruby-talk@netlab.co.jp > Subject: [ruby-talk:11945] singleton classes? > > > 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. Since there is difference between ``Class method'' and ``instance method'' you need to be a little bit carefull. Effectively a singelton method of the class object A = Class.new # is the same as a class method of the class A - def A.print_name p "my name is #{self}" end A.print_name # => "my name is A" # thus if you define class B < A end # you also inherited the class method #print_name - i.e. B.print_name # => "my name is B" will work. Note class Class is special since you cannot subtype class Class. If you want to add ``instance methods'' somewhat automatically you can think about using the `include Module'' mechanism. Christoph