2

I'm trying to generate a long Latex document with Ruby. If I use a normal heredoc-type declaration, Ruby detects backslashes (of which there are many in Latex) as Unicode escapes:

doc = <<DOC
\underline{FOO}
DOC #=> invalid Unicode escape \underline{FOO}

If I put single quotes around DOC it'll treat the whole thing as a string literal:

doc = <<'DOC'
\underline{FOO}
DOC
puts doc #=> \underline{FOO}

That's fine, but now I can't use string interpolation:

foo = "foo"
doc = <<'DOC'
string interpolation says "#{foo}".
DOC
puts doc #=> string interpolations says "#{foo}".

I'd like the best of both worlds, i.e. string interpolation, and not having to escape every backslash. Is this possible?

1 Answer 1

2

I'd like the best of both worlds, i.e. string interpolation, and not having to escape every backslash. Is this possible?

Not really using straight Ruby. The problem is, you're running headlong into Ruby's intended behavior when handling strings and backslashes.

Generally these are used with Rails to output HTML, but an alterate way to get where you're going might be to use ERB or Erubis and their associated templates. They are processed outside of Ruby's normal string processing but allow you to embed variables. They don't use the familiar #{foo} interpolation, but support

string interpolation says "<%= foo %>".

Erubis is a compiled version of ERB so it runs a lot faster. ERB comes with Ruby, so take your pick.

Sign up to request clarification or add additional context in comments.

1 Comment

I've been told I excel at thinking outside of the box. I think it's because I'm brain damaged. :-) ERB/Erubis is really flexible and could be used for generating email, word-processing documents, or even XML. I think that's its problem - it doesn't do only one thing and it's not really flashy, so it gets overlooked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.