From: Ara.T.Howard@... Date: 2005-05-16T00:55:30+09:00 Subject: Re: infinite number of singleton_classes On Sun, 15 May 2005, Lionel Thiry wrote: > Hello! > > ----8<---- > a = Object.new > > b = class << a > class << self > class << self > class << self > # "class << self".times(n) > self > # "end".times(n) > end > end > end > end > # => #>>>> > ----8<---- > > How many levels can we reach? It seems there is no limit. > > I suppose those singleton_class exists only when needed? Otherwise, I really > wonder where does ruby hide all those singleton_classes... > > But, sincerely, is it needed to have the singleton_class of a singleton_class? > Isn't it a non-sense? Shouldn't this raise an error? > > ---8<--- > a = Object.new > > begin > b = class << a > class << self > self > end > end > rescue NewError > puts "Sincerely, you don't need the singleton_class of the singleton_class!" > end > ---8<--- > > What do you think of it? Isn't it worth an RCR? i've found them useful in the following situation: harp:~ > cat a.rb class C class << self class << self def class_method_generator name module_eval <<-code def #{ name }; @#{ name }; end alias #{ name }? #{ name } def #{ name }= value; @#{ name } = value; end code end end %w( a b c ).each{|meth| class_method_generator meth} end end class B < C end C.a = 42 p C.a B.a = 'forty-two' p B.a C.class_method_generator :x harp:~ > ruby a.rb 42 "forty-two" a.rb:25: undefined method `class_method_generator' for C:Class (NoMethodError) granted, you could do this with a private class method of C - but this is what singleton methods are for : defining a method on 'this' instance right here and right now that only that instance should be able to do. in this case the instance happens to be a singleton of a singleton. in any case i don't think one can say when/if that construct would be useful a priori and think that having that notion enforced by ruby itself ( __i__ know when need a singleton class and __you__ don't ) is the kind of exception that reminds of of a 'p' language. ruby programmers are continually pushing the boundries of oo coding precisely because matz has given them the tools to do so and it would be a shame to take a tool away just because someone hasn't figured out something indespesible to do with that particular tool __yet__. kind regards. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================