Re: what exactly does obj.is_a? do?

From: Jon G. [mailto:[email protected]]

To clarify, I’m interested in how, not if, is_a?
determines whether
@my_obj.is_a?(Klass) with no concern for superclasses or modules. I’m
fairly confident it’s going to take somebody familiar with
Ruby’s source
code, not just the API, to answer this one.

The source code is readily available. Here, from object.c, is the answer
to your question. (Out of curiosity, why are you so curious as to the
internals?)

VALUE
rb_obj_is_kind_of(obj, c)
VALUE obj, c;
{
VALUE cl = CLASS_OF(obj);

switch (TYPE(c)) {
  case T_MODULE:
  case T_CLASS:
  case T_ICLASS:
break;

  default:
rb_raise(rb_eTypeError, "class or module required");
}

while (cl) {
if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
    return Qtrue;
cl = RCLASS(cl)->super;
}
return Qfalse;

}

Gavin K. wrote:

The source code is readily available. Here, from object.c, is the answer
to your question. (Out of curiosity, why are you so curious as to the
internals?)

Thanks Gavin. Unfortunately, my C skills are very rusty. It seems to
boil down to this line…

if (cl == c || RCLASS(cl)->m_tbl == RCLASS©->m_tbl)

but it’s not clear to me if object_id’s are critical here or not. Would
it be possible for cl and c to be different objects, and still be
evaluated by this condition as equal?

To satisfy your curiosity, this was due to an issue we were having with
comparing a cached object to an apparently reloaded class and finding
that the object was not of that class when we thought it should be.
Since my original post we’ve identified the issue/solution with our
caching routine, so at this point this thread is pretty much just about
knowledge for it’s own sake.