在Ruby中,%i或%I是什么意思?

110

%i%I在Ruby中的含义是什么?

我在Google上搜索了一下

"%i or %I" ruby

但我没有找到与Ruby相关的任何内容。

3个回答

160
%i[ ] # Non-interpolated Array of symbols, separated by whitespace
%I[ ] # Interpolated Array of symbols, separated by whitespace

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

在IRB中的示例:

%i[ test ]
# => [:test]
str = "other"
%I[ test_#{str} ]
# => [:test_other] 

2
也被称为%符号表示法。请参阅https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation - anothermh
1
这是正确的。但我不建议使用%I - Mark Thomas
6
@MarkThomas,为什么你不推荐使用%I?你能详细说明一下吗? - Arup Rakshit
1
@ArupRakshit 我的猜测是这样做很丑陋,而使用更明显的字符串插值可以使其更加清晰。 - Joshua Pinter

33
很难找到官方的Ruby文档(在这里)。撰写本文时,当前版本为2.5.1,%i结构的文档可在Ruby字面量的文档中找到。
有一些令人惊讶(至少是对我来说!)的Ruby%构造变体。有通常使用的%i %q %r %s %w %x形式,每种都有一个大写版本以实现插值。 (请参见Ruby literals docs的解释)。
但不仅可以使用方括号[]形式的分隔符,还可以使用任何类型的括号() {} [] <>,并且您可以使用(引用自Ruby文档)“大多数其他非字母数字字符作为百分字符串分隔符,例如“%”、“| ”,“^”等等。”
因此,%i% bish bash bosh %%i[bish bash bosh]的作用相同。

7
Ruby风格指南建议使用方括号,FYI。您可以在Ruby Style Guide中了解更多信息。 - Dmitri

17

这就像%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"]

现在同样的事情也可以用 %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 ]

1
这个回答更清晰地解答了问题。"%I"的使用只是为了从由空格分隔的字符串数组创建哈希键。非常感谢您的回答。 - Vishal Kanaujia
2
@VishalKanaujia 虽然符号经常被用作哈希键,但这并不是它们唯一的用途。在 Ruby 中,哈希键可以是任何东西,而符号可以在许多其他情况下使用。 - tadman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接