From: Lionel Thiry Date: 2005-04-30T05:54:43+09:00 Subject: Re: determining when inside 'class << self' Mark Hubbart a �crit : > On 4/29/05, Florian Gro� wrote: > >>Lionel Thiry wrote: >> >> >>>> class << [] >>>> p inside_metaclass? #=> true >>>> end >>> >>>Sorry for the newbie question, but what does this mean? >> >>class << obj enters the idioclass of an object which is a class that >>contains method that will only be defined for that particular object. > > > Florian: Great explanation. Yeah, great. :) But I already knew about the singleton methods and their container object, the said idioclass. But I didn't know well all the subtleties of 'class << obj', hence my initial question. > > Lionel: If 'class << []' itself seems a little odd to you, read on... > Ok, I read, I read! :) > The class << obj notation can be used in ways that you might not > expect. Since ruby syntax is not as ridged as some other languages, > any expression can take the place of 'obj' in that notation. For > example, if you want to create a temporary/mock object of some sort: > > def clear > class << (a = Object.new) > def inspect() `clear` end > end > end > > (this example was pulled right out of my irbrc) > > As you can see, 'a' was assigned to, and then the resulting object was > opened for modification. So this code: > > class << [] > # do stuff > end > > .. just creates an anonymous array and opens it's metaclass (or > idioclass or singleton class or virtual class, whatever). However, the > array is never assigned to a variable, so it will probably be garbage > collected pretty soon. You will probably never see this exact thing in > someone's code, but it is possible. This probably explains why it was so odd to me, I've mainly met the 'class << self' version. Thanks a lot to you all! :) -- Lionel Thiry Personal website: http://users.skynet.be/lthiry/