我喜欢字符串数组的文字表达式:
%w( i can easily create arrays of words )
我想知道是否有一个文字来获得一个符号数组。我知道我能做
%w( it is less elegant to create arrays of symbols ).map( &:to_sym )
但如果只是用字面意思,那就太棒了。
是!这在Ruby 2.0.0中是可能的。写它的一种方法是:
%i{foo bar} # => [:foo, :bar]
您也可以使用其他分隔符,因此您也可以编写例如%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-百分比+字符串
不幸的是,在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