Read more

How to: Ruby heredoc without interpolation

Arne Hartherz
March 13, 2013Software engineer at makandra GmbH

When you use heredoc, string interpolation is enabled by default:

x = "Universe"
<<-MESSAGE
  Hello #{x}
MESSAGE
# => "Hello Universe"
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

This may be impractical sometimes. To avoid interpolation in heredoc strings, simply enclose your heredoc marker with single quotes:

x = "Universe"
<<-'MESSAGE'
  Hello #{x}
MESSAGE
# => "Hello #{x}"

That will make the string behave like a single-quoted string, so sequences like \n will be used as they are. You don't need to escape single quotes in your heredoc string (just in case you were wondering).


Bonus: You can also use backticks to send shell commands:

<<-`MESSAGE`
  hostname
  whoami
MESSAGE
# => "happycat\narne\n"
Posted by Arne Hartherz to makandra dev (2013-03-13 18:09)