Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
和之间的差异%{}'';%Q{}'';%q{}';在ruby字符串分隔符中_Ruby_String - Fatal编程技术网

和之间的差异%{}'';%Q{}'';%q{}';在ruby字符串分隔符中

和之间的差异%{}'';%Q{}'';%q{}';在ruby字符串分隔符中,ruby,string,Ruby,String,我正在浏览一个关于ruby的在线教程,发现了这个“通用分隔字符串” 所以我在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'

我正在浏览一个关于ruby的在线教程,发现了这个“通用分隔字符串”

所以我在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的具体用途是什么。

以下是关于它们的一些提示:

%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[]
另一个好资源

除了创建字符串的
%(…)
之外,
%
还可以创建其他类型的对象。与字符串一样,大写字母允许插入和转义字符,而小写字母禁止插入和转义字符

%q(无插值)

%Q(插值和反斜杠)

%(插值和反斜杠)

示例

$ str = 'sushant'

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

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

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

值得注意的是。。。任何符号都可以用作分隔符,而不仅仅是方括号,空格也可以用作分隔符(但不能)。
$ str = 'sushant'

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

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

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