How do I go from String to Symbol and Symbol to String?

September 2, 2014

A Symbol is a very basic Ruby Object; it is just a name, and an internal ID. Symbols are great as keys in a Hash. What you should also remember is that Symbols refer to the same Object throughout a Ruby program. Two strings with the same contents are two different Objects, whereas at any given time there is only one instance of a Symbol. This is very good for memory usage, and it is also quicker to compare two Symbols then comparing two strings, this is because when it comes to Symbols Ruby only compares the IDs of the Objects.

So how do you go about converting a String to a Symbol and vice versa? Easy, as usual with Ruby there are methods that quickly take you from one type to the next.

Ruby exposes the ‘to_s’ method on the Symbol to convert it to a string; the String class has a method called ‘to_sym’ that converts a string to a Symbol.

As you can see in lines 8 and 9 a symbol always has the same object ID and, therefore, we can reason that there is only ever one instance of the Symbol. Now compare that to the String class, the same string representation is two different instances and therefore means more memory usage.

Jim Weirich famously said:

I (generally) use the following rule on string vs. symbols:

(1) If the contents (i.e. the sequence of characters) of the object is important, use a String.

(2) If the identity of the object is important, use a Symbol.

That makes it quite clear when to pick a String and when to pick a Symbol. Happy coding people!


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus