Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#to_sym
() -> ::Symbol
str.to_sym → symbol
string.c
View on GitHub ↗
VALUE
rb_str_intern(VALUE str)
{
VALUE sym;
GLOBAL_SYMBOLS_ENTER(symbols);
{
sym = lookup_str_sym_with_lock(symbols, str);
if (sym) {
// ok
}
else if (USE_SYMBOL_GC) {
rb_encoding *enc = rb_enc_get(str);
rb_encoding *ascii = rb_usascii_encoding();
if (enc != ascii && sym_check_asciionly(str, false)) {
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);
int 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 id = intern_str(str, 0);
sym = ID2SYM(id);
}
}
GLOBAL_SYMBOLS_LEAVE();
return sym;
}
Alias of #intern
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.
Example
"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.
Example
'cat and dog'.to_sym #=> :"cat and dog"