liveBook · Manning

To_sym

As explained in The Well-Grounded Rubyist, Fourth Edition

to_sym is a Ruby conversion method that returns a symbol corresponding to a value's textual representation.

to_sym converts a string into a Symbol representing the same text. Ruby also provides intern as a synonym, while symbol literals use a leading colon. section 8.1.6 section 8.2

Convert a string

"abc".to_sym # => :abc "Converting string to symbol with intern....".intern # => :"Converting string to symbol with intern...." section 8.2

Use to_sym when a symbol is the form required by an operation:

  • Pass a dynamically determined method name to send: some_object.send(method_name.to_sym). section 8.2.3
  • Normalize an argument that may arrive as either a string or symbol, especially for method names or finite sets of labels. section 8.2.3
  • Convert a method-name fragment back to a symbol when comparing it with an array of method names. section 15.2.1
  • Avoid converting strings unnecessarily when the receiving method already accepts strings; to_sym adds no value in that case. section 8.2.3
>> "a".to_sym
=> :a
>> "Converting string to symbol with intern....".intern
=> :"Converting string to symbol with intern...."

Compare to_sym with its synonym intern and inspect the resulting symbol notation. section 8.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines the conversion, demonstrates its synonym, and explains practical selection between strings and symbols.
Examples
Demonstrates irb conversions, dynamic send calls, and removing a bang suffix before calling to_sym.
What it assumes
Assumes familiarity with strings, symbols, method calls, and arrays; teaches symbol construction and string normalization.
What you can do after
Apply it via Ruby to convert strings when an operation requires symbols, while avoiding needless conversions.
How it connects
Connects strings, symbols, send, method names, method introspection, and hash keys.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.