是否有符号数组的字面表示法?

182

我喜欢这种用字面量表达字符串数组的方式:

%w( i can easily create arrays of words )

我想知道是否有一种方法可以获取符号数组。我知道可以这样做:

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

但使用文字直接表示会更好。


这种方法会比只创建一个符号数组或者简单的方法更好吗?嗯。 - Dave Newton
在这种情况下,%w 表示法有什么意义? - m_x
在我看来,符号数组比字符串数组更简洁,而且通常使用较少。但是你的情况可能不同。 - Dave Newton
似乎 Ruby 团队同意我的观点,因为自 Ruby 2 版本以来... - m_x
3
可能是创建符号数组的重复问题。 - sjakobi
2个回答

292

3
谢谢,@MarcelJackwerth在之前已经在评论中提到过了,但为了记录,我会接受你的答案。 - m_x
3
请注意,和其他修饰符一样,可以使用多种其他分隔符。例如 %i[foo bar]%i{foo bar}%i!foo bar!%i%foo bar% - user664833
1
如果您想在TextMate或Sublime Text中支持语法高亮,请查看此gist中的我的修改后的.tmLanguage文件 - Ben Kreeger
1
根据 rubocop 的建议,建议使用 %i[foo bar] - Mapad

27

不幸的是,在Ruby 1.x中,可用的%-分隔符列表受到限制。

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

很遗憾...不过感谢你的链接和列表。我不知道%x,看起来比我使用的反引号符更易读。 - m_x
3
对于那些几乎无法记住现有知识的人来说,这并不是那么不幸的事情(我就是其中之一)。 - tokland
26
在Ruby 2.0中,我们将获得%i用于符号数组,请参见:http://www.ruby-lang.org/zh_TW/news/2012/11/02/ruby-2-0-0-preview1-released/ - Marcel Jackwerth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接