From: Gennady Date: 2004-08-11T07:52:35+09:00 Subject: Re: Singleton class methods David A. Black wrote: > Hi -- > > On Wed, 11 Aug 2004, Gennady wrote: > > >>I meant that "class << self" creates a separate anonymous singleton >>class that is associated (?) with an instance of class "Class" >>representing class "Foo", that is a singleton by itself, of course. That >>was my understanding of "class <<" idiom. >> >>The more I think about it, the more it seems like the same is happening >>when you do "def Foo.bar" as well. >> >>The only difference is that "def Foo.bar" reopens the original singleton >>class for "Foo", where the first occurrence of "class << self" in Foo >>definition creates a new anonymous singleton class (see bellow). > > > I'm not clear on your original/new distinction here. Each object can > have a maximum of one singleton class; so if Foo doesn't have one, it > gets created (when you do "def Foo.meth" or "class Foo; class << self" > or class << Foo). So there's no original vs. new singleton class for > a given object; it's always the same one. irb(main):001:0> class Foo irb(main):002:1> A=10 irb(main):003:1> end => 10 irb(main):004:0> class Foo irb(main):005:1> def self.f1 irb(main):006:2> puts A irb(main):007:2> end irb(main):008:1> end => nil irb(main):009:0> class << Foo irb(main):010:1> A=20 irb(main):011:1> end => 20 irb(main):012:0> class << Foo irb(main):013:1> def f2 irb(main):014:2> puts A irb(main):015:2> end irb(main):016:1> end => nil irb(main):017:0> Foo.f1 10 => nil irb(main):018:0> Foo.f2 20 At least for "def Foo.f1" and "class << Foo" it is not the same one: one holds "A=10" and another -- "A=20". Nevermind, my only point in a reply to the original post was that 2 syntactic forms provide same functionality, but differ in implementation. Looks like I am wrong, implementation is quite similar ;-). > > (And of course the object doesn't have to be a Class object -- it can > be any object.) > > >>When you have >> >>class Test >>end >> >>You can create constants both in >> >>class Test >> A=45 >> def self.f >> end >>end >> >>and in >> >>class Test >> class << self >> A=45 >> def f >> end >> end >>end >> >>cases. The difference is only where they are visible. > > > Yes -- see my earlier post on this point. This is just a case of the > fact that you can define constants in any class scope; and in your > example, both Test and Test's singleton class are Class objects. > > > David >