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

前端之家收集整理的这篇文章主要介绍了在ruby字符串分隔符中的’%{}’,’%Q {}’,’%q {}’之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在通过一个关于ruby的在线教程,发现这个“一般分隔字符串”,
%{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[ ] – Interpolated String (default)

%q[ ] – Non-interpolated String (except for \,[ and ])

示例:

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

Besides %(...) which creates a String,The % may create other types of object. As with strings,an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

猜你在找的Ruby相关文章