liveBook · Manning

Heredoc template

As explained in The Well-Grounded Rubyist, Fourth Edition

A heredoc is Ruby syntax for creating a string from source text extending to a designated terminating delimiter.

A heredoc is a Ruby string, usually multiline, written directly in the program file as a template or data block. The << operator reads text through the next matching delimiter, excluding that delimiter. section 8.1.1

Choose the form that matches the surrounding code:

  • Use <<EOM or another delimiter for ordinary heredocs; the delimiter must otherwise stand alone and flush left. section 8.1.1
  • Use <<-EOM when the terminating delimiter may be indented. section 8.1.1
  • Use <<~EOM to strip leading whitespace, especially for heredocs nested inside method definitions. section 8.1.1

Indented messages

A squiggly heredoc keeps source indentation readable while removing that indentation from the resulting string. A hyphenated heredoc instead permits an indented terminator but preserves the content’s leading spaces.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains delimiters, indentation variants, quoting, and expression placement, but stops short of exhaustive heredoc parsing rules.
Examples
Uses multiline text, SQL, indented class methods, quoted content, array elements, and method arguments as examples.
What it assumes
Assumes basic Ruby string syntax and command-line or irb familiarity while developing the heredoc forms from concrete examples.
What you can do after
Apply heredocs to write multiline strings, SQL, templates, array values, and method arguments with controlled indentation.
How it connects
Connects heredocs with strings, interpolation, SQL queries, method definitions, and irb.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.