From: Robert Klemme Date: 2004-09-15T17:09:52+09:00 Subject: Re: Singleton method on object via define_method? "Mauricio Fern�ndez" schrieb im Newsbeitrag news:20040914113158.GA12061@student.ei.uni-stuttgart.de... > On Tue, Sep 14, 2004 at 07:39:57PM +0900, Robert Klemme wrote: > > > There's at least one case where you can know if the singleton class has > > > been created or not (singletons of singletons). > > > > How come? What's special about singletons here? > > >> o = Object.new > => # > >> class << o; class << self; def foo; "foo" end end end > => nil > >> class << o; class << self; foo end end > => "foo" > >> class << o; class << self; class << self; end end end > => nil > >> class << o; class << self; foo end end > NameError: undefined local variable or method `foo' for #>> > from (irb):5 Hm, but what about: >> 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 => "#" > > > And you can always know > > > if you're using evil.rb, of course :-) > > > > How exactly would you want to do it? I don't see how eval helps here. > > eval is evil, but I really meant evil.rb :-) Oops. I wasn't aware of evil.rb and assumed an evil pun. :-) Shame on me... > >> require 'evil' > => true > >> o = Object.new > => # > >> o.internal.klass.to_i > => 1075690784 > >> class << o; end > => nil > >> o.internal.klass.to_i > => 1076982108 > >> class << o; def foo; end end > => nil > >> ObjectSpace._id2ref(o.internal.klass.to_i/2).instance_methods.include? "foo" > => true > >> klass = ObjectSpace._id2ref(o.internal.klass.to_i/2) > => #> > >> class << o; self end > => #> > > hence > > >> def has_singleton?(obj); obj.class.id * 2 != obj.internal.klass.to_i end > => nil > >> o = "" > => "" > >> has_singleton? o > => false > >> class << o; end > => nil > >> has_singleton? o > => true Hm, well ok. But is there an equivalent without evil.rb, i.e. with "normal" Ruby code? I know that you can access all kinds of internals if you write an extension, but AFAIK you can't know whether there is a singleton class or not. Please correct me if I'm wrong here... Kind regards robert