From: Caleb Clausen Date: 2010-04-26T00:14:19+09:00 Subject: Re: DrX, an object inspector On 4/25/10, Mooffie n/a wrote: > How, for example, can you find an object's class using pure Ruby? > > The problem with Ruby's #class is that it skips singletons. Example: > > s = "blah" > def s.whatever; 666; end > p s.class > > The above will print "String", but it's an error: the class should be > some singleton. > > (Doing "class << s; self; end" isn't a solution because it alters the > object model: it *creates* a singleton if none yet exists.) > > Though maybe there *is* a way to find an object's class, I don't know (I > still consider myself a Ruby newbie). I had thought that I had proved to myself that class<=1.8.6) versions of ruby.... maybe not, tho. I'm not sure now. I might need to change some of my own code in light of this.... Your terminology is a bit wrong, or at any rate unorthodox. Object#class works as it was designed. In the above snippet, the class of s is always a string, even tho its singleton class changes. The #class of an object is its birth type, even tho the type can change subsequently. (The klass field of an object doesn't always point directly to an object's class... klass is kind of misnamed, actually.) Recent vintages of 1.9 are supposed to have Object#singleton_class.