Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 134 ยท Standard Library

Heredocs and sprintf/format

Write multi-line strings with Ruby heredocs (<<~, <<-, quoted terminators) and format text with sprintf, format and String#% - widths, padding, precision and named fields.

Two small features make text-heavy Ruby code pleasant: heredocs let you write long, multi-line strings without a forest of quotes and \n escapes, and format (also called sprintf) lets you lay out numbers and columns precisely. Together they produce reports, SQL, templates, usage messages and aligned tables, all very common jobs.

The basics of strings are in Strings and String Methods. Here we go deeper into the two tools you reach for as soon as the output has to look right.

Heredocs

A heredoc starts with << followed by an identifier, and runs until a line that contains only that identifier. The text in between is the string's value.

Ruby The three heredoc flavours

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

<<~ is the one to use. It finds the line with the least indentation and removes that much from every line, so you can indent the heredoc to match your code and still get clean text. Blank lines are ignored when it measures. Tabs and spaces are both counted as whitespace for stripping, but mixing them confuses it, so stick to spaces.

Raw heredocs and interpolation

By default a heredoc behaves like a double-quoted string: #{...} interpolates, and \n and \t are escape sequences. Quote the identifier with single quotes to get a raw, literal string, which is what you want for regular expressions, shell scripts or code samples that contain #{ and backslashes.

Ruby Interpolated and raw heredocs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In the first heredoc #{user} became grace and \t became a real tab. In the raw one, everything is left exactly as typed.

Calling methods and passing heredocs as arguments

The opening identifier is only a placeholder on the line where it appears. You can keep writing the line, call methods on it, or pass it to a method. The heredoc body starts on the next line.

Ruby Methods on heredocs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When a heredoc is a method argument, the closing identifier sits on its own line after the whole call. Do not interpolate untrusted values into SQL like the last example does with table; it only shows the layout. Use parameters in real code (see ActiveRecord and Sequel Basics).

flowchart TD
  H["<<~TEXT"] --> Q{"How is the<br/>identifier written?"}
  Q -->|"TEXT or &quot;TEXT&quot;"| I["Interpolation and escapes active"]
  Q -->|"'TEXT'"| R["Raw: everything literal"]
  H --> S{"Which marker?"}
  S -->|"<<~"| T["Strip common indentation"]
  S -->|"<<-"| U["Terminator may be indented"]
  S -->|"<<"| V["Terminator at column 1"]

A heredoc has two independent choices: the marker controls indentation, the quoting controls interpolation.

format, sprintf and String#%

format (identical to sprintf) builds a string from a format string that contains plain text and conversion specifications starting with %, plus the values to insert. String#% is the shorthand: "%d items" % 3. Use an array for several values: "%s is %d" % ["Ada", 36].

A specification has this shape, with every part but the conversion letter optional:

TEXT
%  [flags]  [width]  [.precision]  conversion
Ruby The common conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notes on the table above: d formats integers (a float is floored for %d); f fixed decimals; e scientific; g picks whichever is shorter; s calls to_s; p calls inspect; x, o and b are hexadecimal, octal and binary. %.2f rounds, not truncates.

Named and positional fields

Long format strings with many %s get unreadable and fragile. Ruby offers two cleaner forms.

Ruby Named references and reuse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Named references make translations and templates safer, because the order of words can change between languages while the names stay put. %<name>s accepts all format flags; %{name} is simpler but offers no formatting.

Aligned tables and reports

Combine width flags with a heredoc and you get tidy reports. A trick worth knowing: compute the width from the data, then use *.

Ruby A receipt with aligned columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Interpolating a multi-line string into a squiggly heredoc, as lines.join("\n") does above, does not break the stripping: only the literal text of the heredoc is measured, not the interpolated parts. The final line prints the set of line widths, and a single number means every row lines up.

For simple padding you can also use ljust, rjust and center (see String Methods), which are easier to read for one-off cases. format wins once you need numbers, signs or several columns at once.

Thousands separators and money

Ruby's format has no thousands flag. The usual idiom adds the commas with gsub afterwards.

Ruby Adding thousands separators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first helper silently drops the minus sign of a negative number, because scan(/\d{1,3}/) only collects digits; the call with -1234.5 shows it. Always test the edge cases of a helper like this. Real money code would use a locale-aware library or handle the sign first. For exact money arithmetic see BigDecimal, Rational and Complex.

Common mistakes

  • Using << and indenting the terminator. Plain << needs the terminator at column 1. Use <<~.
  • Forgetting '...' for regexes and shell code in heredocs: \d in an interpolated heredoc is not what you want.
  • Putting code after the terminator. Anything on the terminator's line breaks it; the terminator must be alone on its line (leading spaces are allowed for <<~ and <<-).
  • Mismatched arguments to format. Too few raises ArgumentError; extra values are ignored unless $DEBUG is on.
  • Expecting %d to round floats. format("%d", 2.9) is 2. Round first with round.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which heredoc marker removes the common leading indentation from the body?

    <<~ strips the shortest indentation of the body lines from all lines. <<- only lets the terminator be indented.
  2. 2. How do you write a heredoc in which #{x} and backslashes stay literal?

    Single-quoting the identifier makes the heredoc raw: no interpolation and no escape processing.
  3. 3. What does format("%-8s|", "ab") produce?

    Width 8 pads to eight characters, and the - flag left-aligns the text, so the spaces come after it.
  4. 4. Which format string reuses the first argument twice?

    n$ selects the n-th argument, so %1$s can appear many times with only one value supplied.
  5. 5. What does format("%.2f", 2.675) do with the extra digits?

    Precision on f rounds. (A float like 2.675 is stored slightly below or above the decimal value, so for exactness use BigDecimal.)

Summary

  • Prefer <<~ heredocs: they strip common indentation. <<- allows an indented terminator; plain << does not.
  • Quote the identifier with single quotes for a raw heredoc; double quotes or none interpolate.
  • You can chain methods on a heredoc and pass several heredocs to one call.
  • format/sprintf/String#% use %[flags][width][.precision]conversion; the common conversions are d f e g s p x o b c %.
  • Use %<name>s or %{name} for named fields, n$ for positions and * for computed widths.

Next: Threads