是否有符号数组的文字符号?

m_x*_*m_x 167 ruby arrays symbols syntactic-sugar

我喜欢这个字符串数组的文字表达式:

%w( i can easily create arrays of words )
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一个文字来获得一个符号数组.我知道我能做到

%w( it is less elegant to create arrays of symbols ).map( &:to_sym )
Run Code Online (Sandbox Code Playgroud)

但是使用文字就好了.

Dav*_*son 272

是! 现在可以在Ruby 2.0.0中实现.写它的一种方法是:

%i{foo bar}  # => [:foo, :bar]
Run Code Online (Sandbox Code Playgroud)

您也可以使用其他分隔符,因此您也可以编写%i(foo bar)%i!foo bar!例如.

此功能最初在此处公布:

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

Ruby的官方文档中提到了这一点:

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

  • 谢谢,@ MarcelJackwerth已在之前接受的答案的评论中说明了这一点,但我会接受你的后代. (3认同)
  • 请注意,与其他修饰符一样,可以使用一系列其他分隔符.例如`%i [foo bar]`,`%i {foo bar}`,`%i!foo bar!`,`%i%foo bar%`. (3认同)

Gar*_*eth 26

在Ruby 1.x中,遗憾的是,可用的%-delimiters列表是有限的

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
Run Code Online (Sandbox Code Playgroud)

  • 在Ruby 2.0中,我们将获得符号数组的%i,请参阅:http://www.ruby-lang.org/zh_TW/news/2012/11/02/ruby-2-0-0-preview1-released/ (26认同)
  • 好吧,对那些几乎无法将现有的人保持在脑海中的人来说并不是那么不幸(那将是我). (3认同)