String#to_sym
str.to_sym -> symbol Returns:
Symbol · Updated March 13, 2026 · String Methods strings conversion symbols intern
The to_sym method converts a string to its corresponding symbol. Symbols are immutable, interned strings that are efficient for use as hash keys, identifiers, and method names. Each unique string maps to a single symbol object, making to_sym useful for de‑duplication and fast comparison.
Syntax
str.to_sym
The method takes no parameters. It returns a Symbol whose #to_s representation equals the original string.
Parameters
to_sym has no parameters.
Examples
Basic conversion
"hello".to_sym
# => :hello
"foo_bar".to_sym
# => :foo_bar
"123".to_sym
# => :"123" (symbol with numeric characters)
Symbols are interned
a = "hello".to_sym
b = "hello".to_sym
a.object_id == b.object_id
# => true (same symbol object)
c = "world".to_sym
d = "world".to_sym
c.object_id == d.object_id
# => true
Edge cases: empty string and whitespace
"".to_sym
# => :"" (empty symbol)
" ".to_sym
# => :" " (symbol containing spaces)
Non‑ASCII characters
"café".to_sym
# => :café
"🎉".to_sym
# => :🎉
Using symbols as hash keys
hash = { "name" => "Alice", "age" => 30 }
hash.keys.map(&:to_sym)
# => [:name, :age]
Common Patterns
Converting user input to symbols for configuration
def parse_option(input)
case input.to_sym
when :enable
true
when :disable
false
else
raise "Unknown option: #{input}"
end
end
parse_option("enable") # => true
parse_option("disable") # => false
parse_option("invalid") # => raises "Unknown option: invalid"
De‑duplicating strings in a collection
strings = ["foo", "bar", "foo", "baz", "bar"]
symbols = strings.map(&:to_sym).uniq
# => [:foo, :bar, :baz]
Symbolizing hash keys (Rails‑style)
def symbolize_keys(hash)
hash.transform_keys(&:to_sym)
end
symbolize_keys({ "name" => "Alice", "age" => 30 })
# => {:name=>"Alice", :age=>30}
Fast lookup with symbol keys
LOOKUP = { :en => "English", :fr => "French", :es => "Spanish" }
def translate(lang)
LOOKUP[lang.to_sym] || "Unknown"
end
translate("en") # => "English"
translate("fr") # => "French"
translate("de") # => "Unknown"
Errors
to_sym does not raise exceptions for any string input. However, note that symbols are not garbage‑collected in Ruby versions before 3.2, so converting uncontrolled user input to symbols can lead to a memory leak (symbol DoS). In Ruby 3.2 and later, dynamic symbols are garbage‑collected.
Potential memory concerns (pre‑3.2)
# In Ruby < 3.2, repeated conversion of arbitrary strings can cause memory growth
loop do
SecureRandom.hex(10).to_sym
end