Ruby Multiline Strings: Choosing a Literal That Preserves Your Text

How Ruby heredocs, quoted strings and percent literals handle interpolation, escapes and indentation, and when to keep multiline text outside Ruby code.

Putting a block of plain text into a Ruby multiline string looks simple, but the wrong literal form can evaluate a value you meant to keep as text, consume a backslash, or shift indentation. This review covers what each form changes, when the result matches the original text, and when the text is better kept outside Ruby code.

Short verdict

For most multiline text embedded in Ruby source, the squiggly heredoc (<<~) is the most readable choice. You can indent it to match the surrounding code, and Ruby removes that shared indentation from the resulting string. The main tradeoff is between interpolation and fidelity. An unquoted heredoc treats #{...} and backslash sequences as code. A single-quoted heredoc (<<~'TEXT') keeps those characters exactly as written.

Keep the text in a separate plain-text file when any of these apply: the content is long, people who don't write Ruby edit it, it must match byte for byte (including trailing whitespace or specific line endings), or it is also shared outside the codebase.

What the transformation actually changes

Nothing in this transformation is visual. Writing text as a Ruby string literal does not reverse, mirror or restyle characters, and it does not swap in Unicode lookalikes. It only changes how the text is written in source code: the delimiters, the escape sequences and the indentation. Ruby uses those to rebuild the intended characters at runtime. So the question to ask is whether the runtime value equals the original text.

Two layers need to be kept apart. The source representation is what you see in the file and copy from it. The string value is what the program actually holds. An escaped quote or a doubled backslash appears in the source but not in the value. In a squiggly heredoc, the leading indentation appears in the source but is removed from the value.

Ruby's multiline string forms compared

Form | Interpolation | Backslash escapes | Indentation in value | Trailing newline
"..." spanning lines | Yes | Yes | Kept as typed | Only if typed
'...' spanning lines | No | Only \ and ' | Kept as typed | Only if typed
%Q(...) or %(...) | Yes | Yes | Kept as typed | Only if typed
%q(...) | No | Only \ and an escaped delimiter | Kept as typed | Only if typed
<<TEXT | Yes | Yes | Kept; terminator must start the line | After the last content line
<<-TEXT | Yes | Yes | Kept; terminator may be indented | After the last content line
<<~TEXT | Yes | Yes | Common leading indentation removed | After the last content line
<<~'TEXT' | No | None; backslashes are literal | Common leading indentation removed | After the last content line

A few notes on the table:

  • The squiggly heredoc requires Ruby 2.3 or later.
  • A heredoc's value ends with a newline after its last content line. Call .chomp if you don't want it.
  • Double-quoted forms interpolate more than #{...}. A # followed by an instance variable (#@name) or a global variable (#$name) is also interpolated.

Example: squiggly heredoc with interpolation

name = "Ada"
message = <<~TEXT
  Hello, #{name}.
    This line keeps two extra spaces.
  Goodbye.
TEXT

The resulting value, shown as Ruby's inspect output:

"Hello, Ada.\n  This line keeps two extra spaces.\nGoodbye.\n"

Ruby removes the two spaces that all lines share. The middle line keeps its extra two spaces because they go beyond that shared amount. Lines that contain only whitespace are ignored when Ruby works out the shared indentation. Mixing tabs and spaces makes the removed amount harder to predict, so use one consistently inside a heredoc.

Example: preserving text literally

template = <<~'TEXT'
  Price: #{amount}
  Path: C:\temp\new
TEXT

The identifier is in single quotes, so the characters #{amount} stay as plain text and backslashes are not treated as escapes. The path keeps a backslash followed by t and a backslash followed by n. In an unquoted heredoc, the same lines would try to read a variable named amount, turn \t into a tab and turn \n into a line break. Both outcomes silently corrupt the text.

Example: one logical line split across source lines

sql = "SELECT id, name " \
      "FROM users " \
      "WHERE active = true"
# => "SELECT id, name FROM users WHERE active = true"

Adjacent string literals connected by a trailing backslash become one string with no newline characters. This form suits long single-line values that you only want to wrap in the source. Any spaces between fragments must be typed at the ends of the fragments. If they are left out, words run together.

What an escaping converter must handle

If a tool or script converts arbitrary text into a double-quoted Ruby literal, check that its output escapes all of the following:

  • Backslashes, which otherwise start escape sequences.
  • Double quotes, or whichever delimiter is used with %Q.
  • The # character when it is followed by {, @ or $, so that text such as #{x} is not evaluated.
  • Tabs, carriage returns and other control characters, if they need to be visible and unambiguous in the source.

A converter that outputs a single-quoted heredoc avoids most of this, because Ruby applies no escaping inside it. The remaining constraint is the terminator. No line of the text may consist only of the terminator identifier, with or without leading whitespace. Choose an identifier that cannot appear on its own line in the content.

Don't rely on how the converted source looks. Compare the runtime value with the original instead:

original = File.read("note.txt")
# converted is the literal produced by the tool
p converted                  # shows escapes and the trailing "\n"
puts converted == original   # true only if every character matches

Readability and usability after copying or sharing

Screen readers and search tools handle the string value normally once it is displayed, because no characters are replaced with styled Unicode. The source representation is still code, though. Anyone reading the file, including someone using a screen reader, will encounter delimiters and escape sequences. If the text is user-facing, review, translate and publish the plain-text value, not the literal.

Where you copy from matters. Copying the literal from a source file gives you the source form. Copying printed program output gives you the value. Whitespace is part of the value in every form:

  • An editor set to trim trailing whitespace or convert tabs to spaces can change heredoc content without any visible sign.
  • In a squiggly heredoc, re-indenting the whole block is safe. Changing the indentation of individual lines relative to each other changes the value.

Pasting code through rich-text tools, such as word processors and some chat or email clients, can replace straight quotes with typographic quotes or alter whitespace. Either change breaks the literal or changes its value. No specific destination was tested for this review, so check the tools you actually use, or share code as an attachment or in a code-formatted block.

Ruby treats source files as UTF-8 by default (since Ruby 2.0), so non-ASCII text can usually be pasted directly into a literal. Where the file encoding or tooling is uncertain, double-quoted forms accept \u escapes as an alternative. If a source file uses Windows line endings, check whether carriage-return characters end up in your string values in your setup. The evidence available for this review doesn't settle that point.

Gaps in this review

No specific converter tool, test results or version-by-version measurements were supplied. The behavior described here is general, documented Ruby language behavior, not the output of a tested product. Confirm edge cases in your Ruby version, especially tab handling in squiggly heredocs and line-ending treatment, by comparing values as shown above.