8

Alternative Ruby Symbol Literals

 4 years ago
source link: https://avdi.codes/alternative-ruby-symbol-literals/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Periodically I take episodes from the RubyTapas archives and publish them for free. This episode from October 2012 is about symbol literals, and how you can use alternative quoting syntax to embed and interpolate any kind of character sequence in a symbol. And also: why you might not want to take advantage of this. Enjoy!

swatch
Video Thumbnail
Video Thumbnail

Video Script

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

:foo

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!

MVIMG_20190508_175746.jpg?resize=770%2C770&ssl=1

Let's correspond!

May I write to you? Every week or so you'll get a SIGAVDI newsletter with a few handpicked links to interesting articles, talks, or resources; an update on what I've published lately; and some reflections at the intersection of software and life. Replies go directly to me, and I try to respond to every single one (eventually!)


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK