← Back to Ruby Course | Chapter 3: Strings | Lesson 3 of 7

Heredoc

A heredoc is a way to write a long block of text between two markers, like a letter placed between a start and end line. It keeps the layout tidy for big pieces of text.

In this page:

  1. Heredoc
Syntax
ruby
text = <<~IDENTIFIER
  first line
  second line
IDENTIFIER
puts text

Heredoc

A heredoc, started with <<~IDENTIFIER and ended with a matching IDENTIFIER on its own line, lets you write a large, readable block of multi-line text.

The ~ variant (squiggly heredoc) automatically strips leading indentation, making it easy to keep the heredoc nicely indented with surrounding code. Heredocs support string interpolation just like double-quoted strings.

Note: Prefer <<~ (squiggly heredoc) over the older <<- since it strips common leading whitespace automatically.

Example: Heredoc

markup
name = "World"

text = <<~GREETING
  Hello, #{name}!
  This is a heredoc.
  It can span many lines.
GREETING

puts text
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using <<- or << and expecting indentation to be removed, when only <<~ strips the common indent.
  2. Indenting the closing identifier with << instead of <<~, so it is not recognised.
  3. Quoting the identifier as <<~EOS and expecting #{name} to work, when it stops interpolation.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.