Today’s Ruby Tuesday covers String#to_sym.
String#to_sym
operates on a String object, and turns the string into a Symbol
.
Why would someone want to have a Symbol
instead of a String
?
The main reason is that Symbol
s are created once for the lifetime of a program, and use the same reference. Every reference to the symbol :foo
refers to the same instance of :foo
, and it doesn’t matter when, or where, in the program lifetime it is.
String
s on the other hand are unique objects, so two strings of the same value are not necessarily the same object, and depends on when, where, and how they were created.
"foo".to_sym # => :foo "Foo".to_sym # => :Foo "foo".__id__ == "foo".__id__ # => false :foo.__id__ == :foo.__id__ # => true
One case where this might be useful is where you have to tokenize strings, and are going to want to use them as keys for a map. Think header columns in a CSV file, but please don’t write your own CSV parser, as Ruby has a nice one built in.
"firstName,lastName,preferred name,age".split(",").map(&:to_sym) # => [:firstName, :lastName, :"preferred name", :age]
The other place where you might want to use String#to_sym
is when you are trying to create Symbol
s that cannot easily be created by just using the normal symbol notation.
":foo".to_sym # => :":foo" "peanut butter".to_sym # => :"peanut butter"
–Proctor