From: "Ara.T.Howard" Date: 2005-05-05T09:24:48+09:00 Subject: Class#singleton_of at the risk of totally annoying everyone on this list and not getting any real work done for another day i'm posting some of the code i've scraped out of this week's posts and throwing down a challenge to boot: jib:~/eg/ruby > cat a.rb class Class def singleton class << self; self; end end def singleton? not self.ancestors.include? self end def inside_singleton? singleton? end def singleton_of if singleton? m = %r/^(?:#+)$/io.match inspect singleton_name, brackets = m[1], m[2] n = brackets.size - 1 klass = klass_stamp singleton_name n.times{ klass = class << klass; self; end } klass else nil end end def klass_stamp hierachy relatives = hierachy.split %r/::/ parent = Object while((child = relatives.shift)) klass = parent.const_get child parent = klass end klass end end module M class C p singleton_of # => nil class << self p singleton_of # => M::C class << self p singleton_of # => # class << self p singleton_of # => #> end end end end end # # we now explode here # class << self p singleton_of end jib:~/eg/ruby > ruby a.rb nil M::C # #> a.rb:28:in `const_get': wrong constant name #