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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)