简体   繁体   中英

How to handle backslash “\” escape characters in q string and heredocument

Ruby Newbie here. I do not understand why Ruby looks inside %q and escapes the \\ .

I am using Ruby to generate Latex code. I need to generate \\\\\\hline which is used in Latex for table making. I found \\\\\\hline as input generated \\hline even though the string was inside %q .

Here is 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

 \\hline

Ruby does give the warning

   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 )

file = open('foo4.txt', 'w')
str = r"""\\\hline"""
file.write(str)
file.close()

And the file again contains \\\\\\hline as expected.

Am I doing something wrong in 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. 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. They're typically used when a string contains quotes themselves (HTML is a typical example), so it's to avoid noisy quote escaping.

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.

puts %q[\\\\\\hline 'some words']

# >> \\\hline 'some words'

https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM