From: Robert Klemme Date: 2004-09-16T07:39:49+09:00 Subject: Re: Singleton method on object via define_method? "Mauricio Fern�ndez" schrieb im Newsbeitrag news:20040915170634.GA25725@student.ei.uni-stuttgart.de... > On Wed, Sep 15, 2004 at 09:49:50PM +0900, Robert Klemme wrote: >> > > >> o = Object.new >> > > => # >> > > >> class << o; class << self; def to_s ; "foo" end end end >> > > => nil >> > > >> class << o; class << self;to_s end end >> > > => "foo" >> > > >> class << o; class << self; class << self; end end end >> > > => nil >> > > >> class << o; class << self; to_s end end >> > > => "#" >> > >> > It's using Module#to_s because the klass of the singleton class is >> > no longer itself... Module#to_s ends up calling >> > class << o; self.to_s end >> > which you defined before. >> >> Well yes, but the fact remains that there is a singleton we don't know >> of, >> do we? Probably I don't see clearly your point so I'd appreciate it if >> you'd elaborate it. > > It is I who doesn't understand what the above is supposed to prove :) Utter confusion on all sides. :-))) My understanding: someone (I?) made a remark about the fact (well, assumed fact) that you can't test whether an instance has a singleton class. You can access it, but you will not know whether it was created for this access or whether it existed before. You then presented the example with a NameError due to undefined method foo. I thought, you use the NameError for detecting the singleton class, hence I used to_s which I know is always defined and thus would not trigger the exception. The idea being to disprove the test. Maybe I got something wrong here... > Before creating the singleton class of the singleton of o's singleton > class, to_s returned "foo", afterwards it returns "#"... > And anyway, nobody forces us to use to_s > > batsman@tux-chan:/tmp$ cat dfg.rb > class Class > # only works for singletons of singletons, will always return > # true otherwise > def has_singleton? > m = "__magic_#{Time.new.to_i}_#{rand(100000)}" > class_eval do > remove_method(m) rescue nil > define_method(m) { } > begin > send m > rescue NameError > return true > ensure > remove_method m > end > end > false > end > end I'm not sure whether I fully understand what the test should do. But it's late and I'll better go to bed now. A brain with some sleep thinks better... > o = Object.new > klass = class << o; class << self; self end end > p klass.has_singleton? > class << klass; end > p klass.has_singleton? > > batsman@tux-chan:/tmp$ ruby dfg.rb > false > true Hm, but what does this tell me: >> o = Object.new => # >> klass = class << o; self end => #> >> klass.has_singleton? => true The answer is definitely wrong, because the singleton class of o does not have a singleton klass. Hm... For the moment I'll stick with my statement that it's generally not possible to determine whether an instance has a singleton or not other than by using some kind of extension. :-) Kind regards robert