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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With