2.3. Using Here-Documents

If you want to represent a long string spanning multiple lines, you can certainly use a regular quoted string:

str = "Once upon a midnight dreary,
       While I pondered, weak and weary..."

However, the indentation will be part of the string.

Another way is the here-document, a string that is inherently multiline. (This concept and term are borrowed from older languages and contexts.) The syntax is the << symbol, followed by an end marker, then zero or more lines of text, and finally the same end marker on a line by itself:

str = <<EOF
Once upon a midnight dreary,
While I pondered weak and weary,...
EOF

Be careful about things such as trailing spaces on the final end marker line. Current versions of Ruby will fail to recognize ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.