[英]How to handle backslash “\” escape characters in q string and heredocument
Ruby Newbie here. Ruby Newbie在这里。 I do not understand why Ruby looks inside
%q
and escapes the \\
. 我不明白为什么Ruby会在
%q
内部查找并转义\\
。
I am using Ruby to generate Latex code. 我正在使用Ruby生成Latex代码。 I need to generate
\\\\\\hline
which is used in Latex for table making. 我需要生成
\\\\\\hline
,它在Latex中用于制作表格。 I found \\\\\\hline
as input generated \\hline
even though the string was inside %q
. 我发现
\\\\\\hline
作为输入生成\\hline
即使字符串在%q
。
Here is MWE 这是MWE
#!/usr/local/bin/ruby -w
tmp = File.open('foo.txt','w')
str = %q[\\\hline]
tmp.write(str)
tmp.close
The file foo.txt
has this 文件
foo.txt
有这个
\\hline
Ruby does give the warning Ruby确实发出警告
warning: encountered \r in middle of line, treated as a mere space
But this should not be generated since this is supposed to be escaped strings? 但这不应该生成,因为应该将其转义为字符串?
Now I tried it with Python multiline raw strings (similar to Ruby's %q
) 现在,我尝试使用Python多行原始字符串(类似于Ruby的
%q
)
file = open('foo4.txt', 'w')
str = r"""\\\hline"""
file.write(str)
file.close()
And the file again contains \\\\\\hline
as expected. 并再次按预期包含
\\\\\\hline
。
Am I doing something wrong in Ruby? 我在Ruby中做错了吗?
ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [i686-linux]
str = <<'TEXT'
hello %s
\\\hline
%s
TEXT
name = "Graig"
msg = "Goodbye"
puts str % [name, msg]
The heredoc does not have escape chars when it's delimiter is in single quotes. 当定界符位于单引号中时,heredoc没有转义字符。 It does have a form of interpolation.
它确实具有插值形式。 The code above has this output:
上面的代码具有以下输出:
hello Graig
\\\hline
Goodbye
More fancy is using a hash for interpolation: 更花哨的是使用哈希进行插值:
str = <<'TEXT'
hello %{name}
\\\hline
%{msg}, %{name}
TEXT
puts str % {name: "Graig", msg: "Goodbye"}
Output: 输出:
hello Graig
\\\hline
Goodbye, Graig
%q
and %Q
are alternatives to single-quoted and double-quoted strings, respectively. %q
和%Q
分别是单引号和双引号字符串的替代方案。 They're typically used when a string contains quotes themselves (HTML is a typical example), so it's to avoid noisy quote escaping. 通常在字符串本身包含引号的情况下使用它们(HTML是一个典型示例),因此是为了避免嘈杂的引号转义。
Single-quoted strings offer no string interpolation and no escaping. 单引号字符串不提供字符串插值且不转义。 Except for two exceptions: the single quote and the backslash itself.
除了两个例外:单引号和反斜杠本身。 In a
%q
string you don't need to escape the quote, but need to escape the backslash. 在
%q
字符串中,您不需要转义引号,而无需转义反斜杠。
puts %q[\\\\\\hline 'some words']
# >> \\\hline 'some words'
https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.