Skip to content

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

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"
See also #intern #to_str #tr #to_s also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0