Ruby's Object#respond_to?: String or Symbol?

Posted

When calling Object#respond_to?, use a Symbol when you can. Ruby’s internal method lookup uses “IDs,” which correspond to programmer-visible Symbols.

To get an ID from a Symbol, the Ruby interpreter uses a bit-shift, SYM2ID:

#define SYM2ID(x) RSHIFT((unsigned long)x,8)

To get an ID from a String, on the other hand, it does this:

static ID
str_to_id(str)
    VALUE str;
{
    VALUE sym = rb_str_intern(str);

    return SYM2ID(sym);
}

…and since that calls SYM2ID anyway, and we assume the shortest path between two points is a straight line, your code will be more efficient if it uses a Symbol.

Be wary of premature optimization, too: this tip is really to justify a convention, not to encourage you to rewrite all your code.