Is there a literal notation for an array of symbols?

RubyArraysSymbolsSyntactic Sugar

Ruby Problem Overview


I like this literal expression for an array of strings:

%w( i can easily create arrays of words )

I am wondering if there is a literal to get an array of symbols. I know I can do

%w( it is less elegant to create arrays of symbols ).map( &:to_sym )

but it would be so wonderful just to use a literal.

Ruby Solutions


Solution 1 - Ruby

Yes! This is possible now in Ruby 2.0.0. One way to write it is:

%i{foo bar}  # => [:foo, :bar]

You can also use other delimiters, so you could also write %i(foo bar) or %i!foo bar! for example.

This feature was originally announced here:

http://www.ruby-lang.org/zh_TW/news/2012/11/02/ruby-2-0-0-preview1-released/

It is mentioned in the official documentation of Ruby here:

http://ruby-doc.org/core/doc/syntax/literals_rdoc.html#label-Percent+Strings

Solution 2 - Ruby

In Ruby 1.x, unfortunately the list of available %-delimiters is limited

Modifier	Meaning
%q[ ]		Non-interpolated String (except for \\ \[ and \])
%Q[ ]		Interpolated String (default)
%r[ ]		Interpolated Regexp (flags can appear after the closing delimiter)
%s[ ]		Non-interpolated Symbol
%w[ ]		Non-interpolated Array of words, separated by whitespace
%W[ ]		Interpolated Array of words, separated by whitespace
%x[ ]		Interpolated shell command

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionm_xView Question on Stackoverflow
Solution 1 - RubyDavid GraysonView Answer on Stackoverflow
Solution 2 - RubyGarethView Answer on Stackoverflow