From: Kyle Putnam Date: 2004-08-11T09:04:12+09:00 Subject: Re: Singleton class methods On Tue, 2004-08-10 at 19:27, David A. Black wrote: > Hi -- > > <> > > It's the same as with any class: you can open its scope with the > 'class' keyword (using "<< obj" to indicate the anonymous class you > want), or you can capture it in a constant or variable and class_eval > from there, and so on. For example (using a non-Class object, just > for a change of pace :-) > > x = "hi" > class << x > C = 1 > end > > xclass = (class << x; self; end) > > puts xclass::C # => 1 > > This (class << x; self; end) thing is rather unwieldy, but there's an > RCR pending for Kernel#singleton_class, which would then do for an > object's singleton class what #class does for its class of origin. > Here's that method, plus the above example rewritten to use it: > > module Kernel > def singleton_class; class << self; self; end; end > end > > x = "hi" > x.singleton_class::C = 1 # (or const_set if you prefer) > p x.singleton_class::C # => 1 > > > David That makes it crystal clear! I was looking specifically for what you demonstrated with xclass = (class << x; self; end). Kernel#singleton_class seems like a great idea - had I seen that listed from Object#methods it would've been obvious :) Thanks! Kyle