【问题标题】:Is there a literal notation for an array of symbols?符号数组是否有文字符号?
【发布时间】:2012-02-07 16:01:21
【问题描述】:

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

%w( i can easily create arrays of words )

我想知道是否有文字来获取符号数组。我知道我能做到

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

但如果使用文字就太好了。

【问题讨论】:

  • 这种方法会比创建符号数组更好吗?还是简单的方法?嗯。
  • 在这种情况下,%w 符号的意义何在?
  • IMO 符号数组比字符串数组更简洁,而且通常不太常见。 YMMV。
  • 似乎 ruby​​ 团队从 ruby​​ 2 开始就同意我的意见...
  • Create array of symbols的可能重复

标签: ruby arrays symbols syntactic-sugar


【解决方案1】:

是的!这在 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-Percent+Strings

【讨论】:

  • 谢谢,@MarcelJackwerth 已经在对先前接受的答案的评论中说明了这一点,但我会接受你的后代。
  • 请注意,与其他修饰符一样,可以使用一系列其他分隔符。例如%i[foo bar], %i{foo bar}, %i!foo bar!, %i%foo bar%.
  • 如果您想在 TextMate 或 Sublime Text 中突出显示对此的支持,请查看 my modified .tmLanguage file in this gist
  • 根据rubocop,建议使用%i[foo bar]
【解决方案2】:

不幸的是,在 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

【讨论】:

  • 太糟糕了......不过,感谢您的链接和列表。不知道%x,似乎比我使用的反引号更易读
  • 好吧,对于那些几乎无法将现有内容留在脑海中的人(那就是我)来说,这并不是那么不幸。
  • 在 Ruby 2.0 中,我们将获得符号数组的 %i,参见:ruby-lang.org/zh_TW/news/2012/11/02/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2015-01-15
  • 2016-10-27
  • 2010-09-30
  • 1970-01-01
相关资源
最近更新 更多