From: Gennady Date: 2004-08-11T08:28:36+09:00 Subject: Re: Singleton class methods David A. Black wrote: > Hi -- > > On Wed, 11 Aug 2004, Gennady wrote: > > >>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". > > > But only one of them is a singleton class; the other is simply Foo > itself :-) When you do def Foo.m, 'self' is Foo; but when you do class That's where a slight misunderstanding might have occurred: I was calling "Foo itself" an original singleton class (isn't it? ;-)), and the one created by "class << Foo" -- an anonymous singleton class of Foo (i omitted word "anonymous" from my original reply, sorry). > << Foo, 'self' is the anonymous singleton class of Foo. Thus the > constants are different. > > > David >