How to: Ruby heredoc without interpolation

Posted . Visible to the public.

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

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

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"
Arne Hartherz
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2013-03-13 17:09)