Multiline Strings
A multiline string lets you write text that spans several lines exactly as you type it, like a poem on a page. You do not need special line-break marks.
In this page:
Syntax
text = "first line
second line"
puts text
Multiline Strings
A Ruby string literal can span multiple lines directly inside quotes, preserving the line breaks as part of the string's content. This is simpler than using explicit \n characters for short multi-line text.
For longer blocks of text, a heredoc (covered next) is usually more readable.
Note:
Line breaks typed directly inside a quoted string become literal newline characters in the resulting string.
Example: Multiline Strings
message = "Line one
Line two
Line three"
puts message
puts message.lines.count
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
- Adding leading spaces to continuation lines inside quotes and not expecting them in the output.
- Forgetting to close the quote, so the rest of the file is treated as part of the string.
- Counting lines with
split("\n")whenlineskeeps the newline characters.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: