181

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.

Gareth
  • 133,157
  • 36
  • 148
  • 157
m_x
  • 12,357
  • 7
  • 46
  • 60

2 Answers2

291

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

Phil Ross
  • 25,590
  • 9
  • 67
  • 77
David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • 3
    thanks,@MarcelJackwerth already stated it in a comment on the previous accepted answer, but i'll accept yours for posterity. – m_x Jan 26 '13 at 16:48
  • 3
    Note that as with other modifiers, it is possible to use a range of other delimiters. e.g. `%i[foo bar]`, `%i{foo bar}`, `%i!foo bar!`, `%i%foo bar%`. – user664833 Feb 06 '14 at 22:40
  • 1
    If you'd like highlighting support for this in TextMate or Sublime Text, check out [my modified .tmLanguage file in this gist](https://gist.github.com/kreeger/9584625). – Ben Kreeger Mar 16 '14 at 15:10
  • 1
    according to [rubocop](https://github.com/bbatsov/rubocop), it is advised to use `%i[foo bar]` – Mapad Jul 18 '17 at 10:02
27

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
Gareth
  • 133,157
  • 36
  • 148
  • 157
  • too bad... thanks for the link and list, though. did not know `%x`, seems more readable than the backticks notation i use – m_x Jan 11 '12 at 09:38
  • 3
    well, not so unfortunate for those who can barely keep the existing ones in their heads (that would be me). – tokland Jan 11 '12 at 10:42
  • 26
    In Ruby 2.0 we will get %i for symbol arrays, see: http://www.ruby-lang.org/zh_TW/news/2012/11/02/ruby-2-0-0-preview1-released/ – Marcel Jackwerth Nov 17 '12 at 11:00