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:
Syntax
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
name = "World"
text = <<~GREETING
Hello, #{name}!
This is a heredoc.
It can span many lines.
GREETING
puts text
Login to try C/C++/Java/PHP code in the editor
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
- Using
<<-or<<and expecting indentation to be removed, when only<<~strips the common indent. - Indenting the closing identifier with
<<instead of<<~, so it is not recognised. - Quoting the identifier as
<<~EOSand expecting#{name}to work, when it stops interpolation.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: