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
