ruby 符号数组是否有文字表示法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8816877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:40:15  来源:igfitidea点击:

Is there a literal notation for an array of symbols?

rubyarrayssymbolssyntactic-sugar

提问by m_x

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.

但仅使用文字就太棒了。

回答by David Grayson

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

是的!这在 Ruby 2.0.0 中现在是可能的。一种写法是:

%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.

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

This feature was originally announced here:

此功能最初是在此处宣布的:

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

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:

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

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

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

回答by Gareth

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

在 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