我喜欢这种用字面量表达字符串数组的方式:
%w( i can easily create arrays of words )
我想知道是否有一种方法可以获取符号数组。我知道可以这样做:
%w( it is less elegant to create arrays of symbols ).map( &:to_sym )
但使用文字直接表示会更好。
我喜欢这种用字面量表达字符串数组的方式:
%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!
。%i[foo bar]
、%i{foo bar}
、%i!foo bar!
、%i%foo bar%
。 - user664833不幸的是,在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
%w
表示法有什么意义? - m_x