From: Mark Hubbart Date: 2005-05-01T05:31:02+09:00 Subject: Re: instantiating metaclasses, sorta [Was: determining when inside 'class << self'] On 4/30/05, David A. Black wrote: > Hi -- > > On Sat, 30 Apr 2005, Mark Hubbart wrote: > > > While experimenting with this, I discovered something interesting: it > > is possible to instantiate a metaclass. By duping a metaclass, you > > regain the ability to instantiate it, apparently without losing any > > functionality. > > > > name = "Jack Smith" > > def name.reverse > > split.reverse.join ", " > > end > > name.reverse #==> "Smith, Jack" > > > > # dup name's metaclass > > nameclass = class << name; self; end.dup > > > > name2 = nameclass.new "John Doe" > > name2.reverse #==> "Doe, John" > > > > Any thoughts? Am I strange for finding this a bit surprising? > > I find it pretty startling. I've often wondered whether there was a > way to do essentially this. I'd concluded there wasn't. Maybe, at > the time, there wasn't.... Sure enough, this doesn't work in 1.6.8. Also, the singleton class inspects as "String" in 1.6.8, which I find interesting. > I subjected it to one further test, to make sure that the > name2.reverse is actually a different method (since if two objects > were sharing a singleton method, that would have to be considered a > bug): > > class << name > def reverse > "hi" > end > end > > name.reverse # hi > name2.reverse # Doe, John > "hello".reverse # olleh <= just to be totally sure :-) > > Hmmmm, it's still daytime in Paris, so we may yet learn of some > limitation or reason to avoid it... :-) indeed :) cheers, Mark