0
0
Rubyprogramming~5 mins

Heredoc syntax for multiline strings in Ruby

Choose your learning style9 modes available
Introduction
Heredoc lets you write long text across many lines easily, just like writing a paragraph on paper.
When you want to store a long message or letter in your program.
When you need to write code or text that spans multiple lines without using many quotes.
When you want to keep your text neat and readable in your code.
When you want to include formatted text like poems or instructions.
When you want to avoid using many plus signs or backslashes for line breaks.
Syntax
Ruby
<<IDENTIFIER
Your multiline text goes here
IDENTIFIER
The IDENTIFIER can be any word you choose, but it must match at the start and end.
The ending IDENTIFIER must be alone on its line with no spaces before or after.
Examples
Basic heredoc with the identifier TEXT.
Ruby
<<TEXT
Hello,
This is a multiline string.
TEXT
Using <<- allows indentation before the ending identifier.
Ruby
<<-DOC
Line one
Line two
  DOC
Using <<~ removes common leading spaces for neat indentation.
Ruby
<<~MSG
  Indented line one
  Indented line two
MSG
Sample Program
This program stores a multiline greeting message using heredoc and prints it.
Ruby
message = <<~GREETING
  Hello friend,
  Welcome to learning Ruby!
  Enjoy coding.
GREETING

puts message
OutputSuccess
Important Notes
Heredoc keeps the line breaks exactly as you write them, so your text looks the same when printed.
Using <<~ helps keep your code tidy by removing extra spaces at the start of each line.
Make sure the ending identifier is not indented unless you use <<- or <<~.
Summary
Heredoc lets you write long text easily across many lines.
Use <
<<~ helps remove extra spaces so your code stays clean and readable.