Ruby Programming/Here documents

For creating multiple-line strings, Ruby supports here documents (heredocs), a feature that originated in the Bourne shell and is also available in Perl and PHP.

Here documents
To construct a here document, the  operator is followed by an identifier that marks the end of the here document. The end mark is called the terminator. The lines of text prior to the terminator are joined together, including the newlines and any other whitespace.

The result:

If we pass the  function multiple arguments, the string literal created from the here document is inserted into the argument list wherever the   operator appears.

In the code below, the here-document (containing the four grocery items and a blank line) is passed in as the third argument. We get the same output as above.

Multiple here documents
You can also have multiple here documents in an argument list. We added a blank line at the end of each here document to make the output more readable.

The output after running this code is:

We have been using the  function in our examples, but you can pass here documents to any function that accepts Strings.

Indenting
If you indent the lines inside the here document, the leading whitespace is preserved. However, there must not be any leading whitespace before the terminator.

The result:

Indenting the terminator
If, for readability, you want to also indent the terminator, use the  operator.

Note, however, that the whitespace before each line of text within the here document is still preserved.

Quoting rules
You may wonder whether here documents follow single-quoting or double-quoting rules.

Double-quoting rules
If there are no quotes around the identifier, like in our examples so far, then the body of the here document follows double-quoting rules.

The output of this example is:

Double-quoting rules are also followed if you put double quotes around the identifier. However, do not put double quotes around the terminator.

Single-quoting rules
To create a here document that follows single-quoting rules, place single quotes around the identifier.

The result: