From: Greg McIntyre Date: 2003-11-30T18:07:09+09:00 Subject: Re: class << x, singletons Oops, let me just untabify that for you... untabify There. :-) Gavin Sinclair wrote: > The alternative you offer is invalid, because it treads on a valid > concept in Ruby: classes within classes. Oops! I think I was a bit tired when I wrote that! :-) Sorry. > It took a bit of mental gymnastics to understand... > class A > class << self > ... > end > end [snip] > I've never been put out by the syntax that Ruby has to > offer in this regard, and see no need for an alternative. Isn't that contradictory? -- It took mental gymnastics to understand, but never put you out? My limited intelligence prevents me coming up with good alternatives, however I still think that the syntax "class << x" is a language wart. Here are some more carefully considered (but probably flawed) alternatives which look clearer to me: 0) Syntax "class << x" (for comparsion) class A; end class B; end b = B.new class << A # add singleton methods to A def f; end end class << b # add singleton methods to b def f; end end A.f b.f class A class << self # add singleton methods to A def x; end end end A.x 1) Method Object#anonymous_class class A; end class B; end b = B.new A.class # => Class A.anonymous_class # => # b.class # => B b.anonymous_class # => class A.anonymous_class # add singleton methods to A def f; end end class b.anonymous_class # add singleton methods to b def f; end end A.f b.f class A class anonymous_class # add singleton methods to A def x; end end end A.x (2) Keyword 'singleton' Keyword/special method called 'singleton' which opens an object's anonymous class for editing. Argument defaults to 'self'. class A; end class B; end b = B.new singleton A # add singleton methods to A def f; end end singleton b # add singleton methods to b def f; end end A.f b.f class A singleton # add singleton methods to A def x; end end end A.x (3) Method Object#singleton{|anonymous_class| ... } Like the keyword, but as a method which takes a block which assigns to 'self'. class A; end class B; end b = B.new A.singleton do |self| self.to_s # => "#" def f; end # defines self.f end b.singleton do |self| self.to_s # => "#>" def f; end # defines self.f end A.f b.f class A singleton do |self| # add singleton methods to A def x; end # defines self.f end end A.x ------- I think I was trying to suggest alternative (1) but without enough sleep to distinguish between an object's class and an object's anonymous class, and without checking what I'd written properly. -- Greg McIntyre ======[ greg@puyo.cjb.net ]===[ http://puyo.cjb.net ]===