%i 或 %I 用 ruby 做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47039716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Whats does %i or %I do in ruby?
提问by american-ninja-warrior
Whats the meaning of %i or %I in ruby?
ruby 中 %i 或 %I 的含义是什么?
I searched google for
我在谷歌上搜索
"%i or %I" ruby
but didn't find anything relevant to ruby.
但没有找到任何与 ruby 相关的内容。
回答by Stanislav Mekhonoshin
%i[ ] # Non-interpolated Array of symbols, separated by whitespace
%I[ ] # Interpolated Array of symbols, separated by whitespace
The second link from my search results http://ruby.zigzo.com/2014/08/21/rubys-notation/
我的搜索结果中的第二个链接http://ruby.zigzo.com/2014/08/21/rubys-notation/
Examples in IRB:
IRB 中的示例:
%i[ test ]
# => [:test]
str = "other"
%I[ test_#{str} ]
# => [:test_other]
回答by Les Nightingill
It can be hard to find the official Ruby documentation (it's here). At the time of writing the current version is 2.5.1, and the documentation for the %i construct is found in the documentation for Ruby's literals.
很难找到官方的 Ruby 文档(在这里)。在撰写本文时,当前版本是 2.5.1,有关 %i 构造的文档可在Ruby 文字的文档中找到。
There are some surprising (to me at least!) variants of Ruby's % construct. There are the often used %i %q %r %s %w %xforms, each with an uppercase version to enable interpolation. (see the Ruby literals docsfor explanations.
Ruby 的 % 构造有一些令人惊讶的(至少对我而言!)变体。有经常使用的%i %q %r %s %w %x形式,每个形式都有一个大写版本以启用插值。(有关解释,请参阅Ruby 文字文档。
But you can use many types of delimiters, not just []. You can use any kind of bracket () {} [] <>, andyou can use (quoting from the ruby docs) "most other non-alphanumeric characters for percent string delimiters such as “%”, “|”, “^”, etc."
但是您可以使用多种类型的分隔符,而不仅仅是[]. 您可以使用任何类型的括号() {} [] <>,并且您可以使用(引用自 ruby 文档)“大多数其他非字母数字字符作为百分比字符串分隔符,例如“%”、“|”、“^”等。
So %i% bish bash bosh %works the same as %i[bish bash bosh]
所以%i% bish bash bosh %工作原理相同%i[bish bash bosh]
回答by tadman
It's like %wand %Wwhich work similar to 'and ":
它就像%wand 的%W工作方式类似于'and ":
x = :test
# %w won't interpolate #{...} style strings, leaving as literal
%w[ #{x} x ]
# => ["\#{x}", "x"]
# %w will interpolate #{...} style strings, converting to string
%W[ #{x} x ]
# => [ "test", "x"]
Now the same thing with %iand %I:
现在与%iand相同%I:
# %i won't interpolate #{...} style strings, leaving as literal, symbolized
%i[ #{x} x ]
# => [:"\#{x}", :x ]
# %w will interpolate #{...} style strings, converting to symbols
%I[ #{x} x ]
# => [ :test, :x ]

