ruby字符串分隔符中’%{}’,’%Q {}’,’%q {}’之间的差异

我正在浏览一篇关于ruby的在线教程,并发现了这个“General Delimited Strings”,

%{a word} # => "a word" %Q{a word} # => "a word" %q{a word} # equivalent to single quoted version. 

所以我在irb上尝试过,这就是我所看到的

 2.0.0p247 :025 > %Q(hi) => "hi" 2.0.0p247 :026 > %q(the) => "the" 2.0.0p247 :027 > %q(th"e) => "th\"e" 2.0.0p247 :028 > %q(th'e) => "th'e" 2.0.0p247 :029 > %Q(h'i) => "h'i" 2.0.0p247 :030 > %Q(h"i) => "h\"i" 

%q和%Q的行为相同,并在双引号中使用字符串。 如果我们可以使用%{}来获得相同的输出,任何人都知道这些2的确切用途。

这里有一些关于它们的提示Ruby_Programming - The % Notation

%Q [] – 插值字符串(默认)

%q [] – 非插值字符串(\,[和]除外)

示例:

 x = "hi" p %Q[#{x} Ram!] #= > "hi Ram!" p %q[#{x} Ram!] #= > "\#{x} Ram!" p %Q[th\e] #= > "th\e" p %q[th\e] #= > "th\\e" # notice the \\ with %q[] 

另一个很好的资源Percent Strings

除了创建String的%(...)之外, %可以创建其他类型的对象。 与字符串一样,大写字母允许插值和转义字符,而小写字母禁用它们。

%q(no interpolation)

%Q(interpolation and backslashes)

%(interpolation and backslashes)

 $ str = 'sushant' $ %q[#{str} "mane"] => "\#{str} \"mane\"" $ %Q[#{str} "mane"] => "sushant \"mane\"" $ %[#{str} "mane"] => "sushant \"mane\""