Use a squiggly heredoc: write text = <<~TEXT, the lines, then TEXT on a line of its own. <<~ removes the indentation the lines share, so the string can sit indented in your code, and it interpolates #{...} like a double-quoted string. Write <<~'TEXT' for no interpolation, and add a method after the opening word, as in <<~SQL.strip, to change the result. For comments, put # on every line.
Ruby has no triple-quoted strings and no backtick template literals: multi-line text is a heredoc, a plain quoted string that spans lines, or a %Q() literal. The sections below cover the squiggly heredoc, the older <<- and << forms and quoted heredocs, calling methods such as strip and lines on a heredoc, quoted strings with line continuation, what single and double quotes change and how newlines reach the output, and multi-line comments, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1The squiggly heredoc: <<~Recommended
A heredoc starts with <<~ and a word you choose (TEXT, SQL, HTML), and the string is every line after it, up to the line holding only that word. The tilde makes Ruby find the smallest indentation among the lines and remove it from each one, so you can indent the text to match the code around it and still get a string that starts at column 0. Extra indentation beyond that is kept. The body interpolates #{...} and reads escapes like \t, just as a double-quoted string does, and the string ends with a newline. The squiggly heredoc was added in Ruby 2.3; it is the form to use today.
name = "Ada" count = 3 # <<~ strips the common leading indentation message = <<~TEXT Hello, #{name}! You have #{count} new messages. This line keeps its extra two spaces. TEXT puts message p message # The closing word can be indented too def help_text <<~USAGE Usage: report [options] -v verbose USAGE end puts help_text p message.end_with?("\n")
Output
The p line shows the real string: "Hello, Ada!\nYou have 3 new messages.\n This line keeps its extra two spaces.\n". The two spaces every line shared are gone, the line indented by four keeps two, and the string ends with \n (end_with? prints true). Inside help_text the body is indented by four and the closing USAGE by two, yet the result starts at column 0. Rails code from before Ruby 2.3 used strip_heredoc from ActiveSupport for this; <<~ replaces it.
2The other heredocs: <<-, << and quoted words
Older code and many Stack Overflow answers use two other forms. With a plain <<TEXT, the closing word must start at column 0 and the text keeps all its indentation. <<-TEXT lets the closing word be indented but still keeps the text's indentation, which is why those answers often call a helper to strip it. The quotes around the word decide how the body is read: a bare or double-quoted word interpolates like "...", and a single-quoted word, <<~'TEXT', takes every character literally, like '...'. That suits templates, regexes and shell snippets full of # and backslashes.
name = "Ada" def show(label, text) puts "#{label}:" p text end # << : the closing word must start at column 0, indentation kept plain = <<TEXT Hi, #{name} TEXT show "<<", plain # <<- : the closing word may be indented, the text is not dash = <<-TEXT Hi, #{name} TEXT show "<<-", dash # <<~ : indentation stripped squiggly = <<~TEXT Hi, #{name} TEXT show "<<~", squiggly # Quote the word for no interpolation or escapes raw = <<~'TEXT' Hi, #{name}\n TEXT show "<<~'TEXT'", raw puts raw
Output
Only <<~ gives "Hi, Ada\n"; << keeps two spaces and <<- keeps four. The quoted heredoc leaves #{name} and \n as typed, which the last line prints as Hi, #{name}\n. Its p form, "Hi, \#{name}\\n\n", escapes the # and the backslash only so that the shown string would read back the same; the string holds no extra backslashes. Leaving a space after << does not start a heredoc: x << TEXT is the append operator.
3Call methods on a heredoc: strip, lines and friends
The opening <<~SQL stands for the whole string, so you can call a method on it right there: <<~SQL.strip drops the final newline, .split.join(" ") squeezes the text onto one line, and .lines splits it into an array. The body still starts on the next line. The same goes for arguments: compare(<<~A, <<~B) opens two heredocs on one line, and their bodies follow one after the other. To go through a string line by line, use lines (an array, each line keeping its \n; pass chomp: true to drop it) or each_line, which yields each line to a block. Rails' squish is ActiveSupport; plain Ruby raises undefined method 'squish' for an instance of String.
# Call a method on the heredoc right after the opening word sql = <<~SQL.strip SELECT name FROM users WHERE active = 1 SQL p sql # One line, the way Rails' squish would make it p <<~SQL.split.join(" ") SELECT name FROM users WHERE active = 1 SQL # Pass heredocs as arguments: the bodies follow in order def compare(a, b) puts "a=#{a.inspect} b=#{b.inspect}" end compare(<<~A, <<~B) first A second B lines = <<~TEXT.lines one two three TEXT p lines p lines.map(&:chomp) <<~TEXT.each_line.with_index(1) do |line, i| alpha beta TEXT puts "#{i}: #{line}" end
Output
strip leaves "SELECT name\nFROM users\nWHERE active = 1" with no trailing newline, and split.join(" ") gives "SELECT name FROM users WHERE active = 1" even though the lines were indented unevenly. The two arguments arrive as "first\n" and "second\n". lines keeps each newline (["one\n", "two\n", "three\n"]), so map(&:chomp) removes them. In the each_line loop, puts adds no second newline because each line already ends with one.
4Quoted strings, %Q() and line continuation
You don't need a heredoc for a string to span lines: a double- or single-quoted string can contain line breaks, and they stay in the string. No indentation is removed, so continuation lines start at column 0. When you only want to break a long line in the source, not in the string, put string literals side by side: Ruby joins adjacent literals into one, and a backslash at the end of a line continues the statement. A backslash just before the line break inside a double-quoted string removes that newline. %Q() works like double quotes and %q() like single quotes, with any bracket pair as delimiters, so the text can contain both kinds of quote without escaping. Coming from JavaScript: backticks in Ruby run a shell command, they are not template literals.
name = "Ada" # A quoted string can simply span lines; the newlines are kept poem = "Roses are red, violets are blue, #{name} writes Ruby" puts poem p poem # Adjacent literals join into one string; \ continues the line long = "This is one long sentence " \ "split over two lines " \ "with no newlines in it." p long # A backslash at the end of a line inside "..." drops the newline joined = "first part, \ second part" p joined # %Q() is like "..." (interpolates), %q() is like '...' p %Q(He said "hi" to #{name} on two lines) p %q(No #{interpolation} in 'here') # Or build it from parts p ["line one", "line two"].join("\n")
Output
The quoted poem keeps its two line breaks and has no trailing newline, unlike a heredoc. The three adjacent literals become one sentence with no \n in it, and the backslash inside the string gives "first part, second part". %Q() interpolated Ada and kept the inner "hi" quotes, while %q() left #{interpolation} alone. Forget the backslash between adjacent literals and the second line becomes a separate statement that Ruby evaluates and discards, so the string silently stops after its first part.
5Single vs double quotes, and newlines in output
Double quotes interpolate #{...} and turn escapes such as \n and \t into a newline and a tab. Single quotes do neither: the only escapes they know are \' and \\, so '\n' is two characters, a backslash and an n. Python and JavaScript treat both quote styles the same; Ruby does not. For output, puts adds a newline unless the string already ends with one, print adds nothing, and p prints the inspect form, with quotes and escapes visible.
name = "Ada" # Double quotes interpolate and read escapes; single quotes don't puts "Hello, #{name}\tbye" puts 'Hello, #{name}\tbye' # "\n" is one newline character, '\n' is a backslash and an n p "a\nb".length p 'a\nb'.length puts "a\nb" puts 'a\nb' # Single quotes only understand \' and \\ puts 'It\'s a backslash: \\' p 'C:\Users\ada' # puts adds a newline unless the string already ends with one puts "one" puts "two\n" print "three" print " and four\n" puts ["x", "y"] puts puts "after an empty puts"
Output
"a\nb".length is 3 and 'a\nb'.length is 4, which is why puts prints the first on two lines and the second as a\nb. In 'C:\Users\ada' the backslashes stay as typed (p shows them doubled: "C:\\Users\\ada"), handy for Windows paths. puts "two\n" prints one line, not two, the two print calls share a line, an array prints one element per line, and a bare puts prints an empty line. Double quotes are the safe default; single quotes are fine when the text has no interpolation or escapes.
6Multi-line comments: # and =begin/=end
Ruby comments start with # and run to the end of the line, and the usual way to comment out a block is a # on every line; most editors do it for a selection with Ctrl+/ or Cmd+/. Ruby also has a block comment: everything between =begin and =end is ignored. Both markers must start at column 0, so a block comment can't follow the indentation of a method body, and style guides (RuboCop among them) recommend # instead. Python readers: Ruby has no docstrings, so a loose string in a method is just an unused value, not documentation.
# The usual way: a # at the start of every line. # Editors add and remove these for a whole block # (Ctrl+/ or Cmd+/ in most of them). puts "start" =begin Everything between =begin and =end is ignored, including code like this: puts "never printed" =end def area(width, height) # Comments inside a method are indented with it width * height end puts area(3, 4) # a comment can also end a line puts "done"
Output
The output is start, 12 and done: the puts between =begin and =end never runs. Indent the markers, as in a method body, and the file no longer parses: Ruby reports main.rb:2: syntax errors found (SyntaxError) and points at each marker with unexpected '=', ignoring it. Text after a line holding only __END__ is not code either; the program can read it through DATA.
7Which should you use?
| Method | Interpolates | Indentation | Best for |
|---|---|---|---|
| <<~TEXT | Yes | Common indent removed | Most multi-line text: messages, SQL, templates |
| <<~'TEXT' | No | Common indent removed | Literal text full of # and backslashes |
| <<-TEXT / <<TEXT | Yes | Kept as typed | Old code; prefer <<~ |
| "line one\nline two" | Yes | Kept as typed | Two or three short lines |
| "a " \ "b" | Yes | No newlines added | One long line split in the source |
| %Q(...) / %q(...) | %Q yes, %q no | Kept as typed | Text with both kinds of quotes |
| =begin / =end | Comment | Must start at column 0 | Rarely; use # on each line |
Frequently asked questions
Does Ruby have triple-quoted strings like Python?
No, but """first line and second line""" across two lines happens to work: Ruby reads it as an empty string, a quoted string that spans the lines, and another empty string, joined into "first line\nsecond line". Write a heredoc (<<~TEXT) or a plain double-quoted string instead, so readers don't wonder.
What is the difference between <<-, << and <<~ in Ruby?
All three start a heredoc. With <<TEXT the closing word must be at column 0; <<-TEXT lets the closing word be indented; neither removes indentation from the text. <<~TEXT (Ruby 2.3+) also strips the indentation the lines share, which is almost always what you want.
How do I write a multi-line string without the newlines?
Split the source line and let Ruby join the pieces: "part one " \ then "part two" on the next line gives one string, as does a backslash at the end of a line inside a double-quoted string. For a heredoc, collapse it afterwards: <<~SQL.split.join(" ") turns every run of spaces and newlines into a single space.
Why is my interpolated text not indented in a <<~ heredoc?
<<~ only removes and keeps indentation in the lines you typed; text inserted with #{} goes in as it is. With inner = "one\ntwo", a body line #{inner} under list: gives "list:\n one\ntwo\n": only the first inserted line gets the two spaces. Indent the inserted text yourself, for example with inner.gsub(/^/, " ").
How do I comment out a block of code in Ruby?
Put # at the start of each line, which your editor can do for a selection (Ctrl+/ or Cmd+/ in most). =begin and =end also work, but only at column 0; indented, they are a syntax error, which is why most Ruby code avoids them.
Is there a squish method in Ruby?
Not in plain Ruby: squish comes from Rails (ActiveSupport), and without it Ruby raises undefined method 'squish' for an instance of String. str.split.join(" ") does the same thing: it trims both ends and turns every run of whitespace, newlines included, into one space.