liveBook · Manning

Percent-style string notation

As explained in The Well-Grounded Rubyist, Fourth Edition

Percent-style string notation is Ruby syntax beginning with a percent sign that creates a string using a selectable delimiter and single- or double-quoted semantics.

Percent-style string notation creates Ruby strings with a percent sign, an optional mode character, and a delimiter: %q produces single-quoted behavior, while %Q and plain %{...} produce double-quoted behavior. section 8.1.1

Choose the form that makes the string easiest to read:

  • %q{You needn't escape apostrophes or quotation marks.} section 8.1.1
  • %Q{The result is #{2 + 2}} and %{The result is #{2 + 2}} both allow interpolation and double-quoted escapes. section 8.1.1
  • Curly braces are common, but paired brackets or repeated nonalphanumeric delimiters also work: %q-A string- and %Q/Another string/. section 8.1.1
%q-A string-
%Q/Another string/
%[Yet another string]

Compare several valid delimiters without changing the basic percent-style notation. section 8.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains %q, %Q, plain percent notation, delimiter matching, interpolation, and escaping, but stops short of exhaustive syntax reference.
Examples
Demonstrates %q, %Q, plain %{...}, alternate delimiters, embedded quotes, interpolation, and escaped unmatched braces.
What it assumes
Assumes awareness of single- and double-quoted strings while clarifying their interpolation and escaping differences.
What you can do after
Apply it to write Ruby strings with readable delimiters and predictable interpolation and escape behavior.
How it connects
Connects percent-style notation with strings, string interpolation, character escaping, and delimiter matching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.