From: Dave Thomas Date: 2001-03-04T06:32:23+09:00 Subject: [ruby-talk:11948] Re: singleton classes? Kevin Smith writes: > Johann Hibschman wrote: > >Could someone either explain singleton classes to me or point me to a > >good explanation? > > Here's a pretty good description: > http://rampages.onramp.net/~huston/dp/singleton.ht > ml Actually, the word 'singleton' in Ruby has two totally different meanings. In the OO sense, it's as you describe: a class that can only have one instance: every request for an object of that class will return the same object instance. The second mean in to do with Ruby's ability to create unique, per-object classes. For example, I might want to create an anonymous subclass for just a particular object: a = [ 1, 2, 3 ] # create an array object b = [ 1, 2, 3 ] # and another class << a def [](n) "element is " + at(n).to_s end end puts a[2] #=> element is 3 puts b[2] #=> 3 Why would you want to do this? Sometimes it's simply a notational convenience. Othertimes, you genuinely need to be able to add features to objects. For example, you might be adding objects to some time of queue in a simulation. Rather than have them all be a subclass of, say, QueueObject, you could instead simply add in the facilties you need on the fly: class << anObj include Queueable end That way any object can be added to a queue. I have to admit I use this rarely, but it's always a nice solution to have in your back pocket. Regards Dave