什么%i或%我做红宝石?

ame*_*ior 38 ruby ruby-on-rails

什么是红宝石中%i或%I的含义?

我搜索了谷歌

"%i or %I" ruby
Run Code Online (Sandbox Code Playgroud)

但没有发现任何与红宝石有关的东西.

Sta*_*hin 59

看来你用google搜索不够:)

%i[ ] # Non-interpolated Array of symbols, separated by whitespace
%I[ ] # Interpolated Array of symbols, separated by whitespace
Run Code Online (Sandbox Code Playgroud)

我的搜索结果中的第二个链接http://ruby.zigzo.com/2014/08/21/rubys-notation/

IRB中的示例:

%i[ test ]
# => [:test]
str = "other"
%I[ test_#{str} ]
# => [:test_other] 
Run Code Online (Sandbox Code Playgroud)

  • @MarkThomas 你为什么不推荐 `%I` 你能详细说明一下吗? (4认同)
  • 又名 [% 表示法](https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation) (2认同)

Les*_*ill 12

很难找到正式的Ruby文档(在此处)。在撰写本文时,当前版本为2.5.1,有关%i构造的文档位于Ruby文字文档中

Ruby的%构造有一些令人惊讶的(至少对我来说是!)变体。有经常使用的%i %q %r %s %w %x形式,每个形式都具有大写形式以启用插值。(有关说明,请参见Ruby文字文档

但是您可以使用多种类型的定界符,而不仅仅是[]。您可以使用任何类型的括号() {} [] <>并且可以(从ruby docs引用)使用“大多数其他非字母数字字符来表示百分比字符串分隔符,例如“%”,“ |”,“ ^”等。”

因此%i% bish bash bosh %%i[bish bash bosh]

  • 仅供参考,[Ruby 样式指南](https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/PercentLiteralDelimiters) 要求使用方括号。 (4认同)

tad*_*man 6

就像%w和的%W工作方式'和和类似"

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"]
Run Code Online (Sandbox Code Playgroud)

现在与%i和相同%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 ]
Run Code Online (Sandbox Code Playgroud)

  • @VishalKanaujia 虽然符号经常用作散列键,但这并不是它们的唯一目的。在 Ruby 中,哈希键实际上可以是任何东西,并且符号可以在许多其他情况下使用。 (2认同)