Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 46 / 68

Multi-Line Strings (Heredoc)

In this lesson you will learn Ruby's heredoc syntax for multi-line strings so you can assemble readable messages. This is for anyone searching for "Ruby heredoc how to use".

The <<~EOT ... EOT form (a heredoc) lets you write a multi-line string with the line breaks included. Adding ~ also strips the extra indentation automatically.

The sample code builds a multi-line message with #{name} embedded, between <<~EOT and EOT. Notice that you can indent the text to match the surrounding code and the extra whitespace is removed for you.

A common stumbling block for beginners is the difference between <<EOT (no tilde) and <<~EOT (with tilde). Without the tilde the indentation ends up inside the string; with it, the indentation is stripped. Not knowing that leaves unintended whitespace in your output.

Being able to write naturally laid-out text without worrying about indentation is what makes the tilde form so convenient. Combined with interpolation #{}, multi-line messages with variables stay concise.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)