Is there a literal notation for an array of symbols?

大兔子大兔子 提交于 2019-11-28 16:15:58
David Grayson

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!