符号数组有文字表示法吗?

发布于 2024-12-26 06:14:00 字数 251 浏览 1 评论 0原文

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

%w( i can easily create arrays of words )

我想知道是否有一个文字可以获取符号数组。我知道我可以做到

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

,但如果只使用文字就太棒了。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娜些时光,永不杰束 2025-01-02 06:14:00

是的!现在在 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

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

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

This feature was originally announced here:

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:

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

分分钟 2025-01-02 06:14:00

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文