Module 1, Topic 6
In Progress

Symbol Literals

Module Progress
0% Complete

Ruby makes a distinction between general-purpose Strings, and immutable, highly-optimized Symbols for use identifiers. One little-known aspect of Symbols is that they can contain all the same kinds of characters as Strings. In this episode, you’ll learn how to use special forms of Symbol literals to manipulate “weird” symbols.

What else do you want to know about working with symbols in Ruby?

As you know, a Symbol literal is a word with a colon in front of it.


You may also know that symbols aren't limited to simple words; anything that can go in a String, can go in a symbol. But how do we get arbitrary characters, like spaces and dashes, into a symbol?

One way is to start with a string and use #to_sym to convert it to a symbol:

"foo-bar (baz)".to_sym          # => :"foo-bar (baz)"

But there's a more concise and idiomatic way to do it. If we precede a quoted string with a colon, it becomes a quoted symbol.

:"foo-bar (baz)"                # => :"foo-bar (baz)"

You can interpolate values into the quoted symbol just as you would into a string.

post_id = 123
:"post-#{post_id}"              # => :"post-123"

And it also works for single-quotes.

:'hello, "world"'               # => :"hello, "world""

Finally, if that doesn't satisfy your symbol-quoting needs, there's also a percent-quote literal syntax. Just like %q for strings, you can quote a symbol with %s followed by any delimiter you want.

%s{foo:bar}                     # => :"foo:bar"

Of course, all these different ways of writing symbols don't mean you should go nuts with generating symbols. Symbols are best used for constrained vocabularies, like the names of options that may be passed to a method. The Ruby virtual machine has to keep a table in memory of all known symbols, so that it can assign a single unique integer ID to each. That means generating an unbounded set of symbols, from, say, user input can lead to memory leaks. So go easy on the symbol interpolation.

That's it for today. Happy hacking!