Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.
"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true
This can also be used to create symbols that cannot be represented using the :xxx notation.
'cat and dog'.to_sym   #=> :"cat and dog"
 
               VALUE
rb_str_intern(VALUE str)
{
    VALUE sym;
#if USE_SYMBOL_GC
    rb_encoding *enc, *ascii;
    int type;
#else
    ID id;
#endif
    GLOBAL_SYMBOLS_ENTER(symbols);
    {
        sym = lookup_str_sym_with_lock(symbols, str);

        if (sym) {
            // ok
        }
        else {
#if USE_SYMBOL_GC
            enc = rb_enc_get(str);
            ascii = rb_usascii_encoding();
            if (enc != ascii && sym_check_asciionly(str)) {
                str = rb_str_dup(str);
                rb_enc_associate(str, ascii);
                OBJ_FREEZE(str);
                enc = ascii;
            }
            else {
                str = rb_str_dup(str);
                OBJ_FREEZE(str);
            }
            str = rb_fstring(str);
            type = rb_str_symname_type(str, IDSET_ATTRSET_FOR_INTERN);
            if (type < 0) type = ID_JUNK;
            sym = dsymbol_alloc(symbols, rb_cSymbol, str, enc, type);
#else
            id = intern_str(str, 0);
            sym = ID2SYM(id);
#endif
        }
    }
    GLOBAL_SYMBOLS_LEAVE();
    return sym;
}
            

Was this page useful?