From: "David A. Black" Date: 2005-05-01T00:23:47+09:00 Subject: Re: instantiating metaclasses, sorta [Was: determining when inside 'class << self'] 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.... 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... :-) David -- David A. Black dblack@wobblini.net