liveBook · Manning

Single-quoted string

As explained in The Well-Grounded Rubyist, Fourth Edition

A single-quoted string is a Ruby string literal delimited by single quotation marks with restricted interpolation and escape processing.

A single-quoted string is a Ruby literal enclosed in apostrophes. It preserves interpolation markers such as #{2 + 2} and treats sequences such as \n and \t literally. section 8.1.1

Use single quotes when you want restricted interpretation:

  • Interpolation does not run, so 'Two plus two is #{2 + 2}.' remains unchanged. section 8.1.1
  • Backslashes generally remain ordinary characters; however, the apostrophe still needs escaping when it appears inside the literal. section 8.1.1
  • Use %q{...} when single-quoted behavior is useful but apostrophes or quotation marks would make ordinary delimiters awkward. section 8.1.1

Literal interpolation

puts "Two plus two is #{2 + 2}." prints 4, whereas puts 'Two plus two is #{2 + 2}.' prints the interpolation text itself. section 8.1.1

puts "Two plus two is #{2 + 2}."
puts 'Two plus two is #{2 + 2}.'

Compare double- and single-quoted interpolation directly. section 8.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains interpolation, apostrophe escaping, backslashes, and the %q alternative through runnable contrasts.
Examples
Demonstrates interpolation markers, newline and tab escapes, apostrophes, irb output, and %q delimiters.
What it assumes
Assumes basic Ruby expression syntax and introduces string-literal behavior through small irb experiments.
What you can do after
Apply single-quoted literals when Ruby should preserve interpolation markers and common backslash sequences as text.
How it connects
Contrasts double-quoted strings, string interpolation, escape sequences, and percent notation.

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.