Write Ruby string literals and escape characters
How Ruby string literals handle escape characters: single vs double quotes, percent literals, heredocs, Unicode escapes, and what survives copying and sharing.
A Ruby string literal is the text you type between delimiters in source code. Escape characters let that literal stand for characters that are hard to type or see, such as newlines, tabs, quotes and invisible Unicode characters. This review covers what escaping changes, which literal form fits which job, and where escaped text stops being readable or behaves unexpectedly after copying.
Short answer: which literal fits which job
Use double quotes when you need escape sequences or interpolation. Use single quotes or %q when the text contains backslashes or # characters that should stay exactly as typed. Use a heredoc for multi-line text. The main benefit of escaping is precision: every character, including invisible ones, is explicit in the source. The tradeoff is readability, because dense escapes are harder to scan, edit and review than ordinary text. Plain text is the better choice for long or user-facing prose, and for content edited by people who are not working in Ruby.
What escaping actually changes
An escape sequence is source-code notation, not a visual effect. When Ruby parses a double-quoted literal, it converts a sequence such as \n into a single newline character. The string held in memory contains that newline, not a backslash followed by the letter n. Nothing about fonts, mirroring or display direction is involved; the change is entirely in which characters are stored. Tools such as p and inspect later show the string in escaped form again, but that output is a representation of the string, not its contents.
single = 'Line one\nLine two'
double = "Line one\nLine two"
single.length # => 18 (backslash and n are two characters)
double.length # => 17 (\n became one newline character)
puts single # prints: Line one\nLine two
puts double # prints the text on two lines
Single-quoted vs double-quoted strings
| Feature | Single quotes ('...') | Double quotes ("...") |
| Interpolation with #{...} | No | Yes |
| Backslash escapes | Only \ and ' | Full set, including \n, \t, \u and \x |
| Percent-literal equivalent | %q(...) | %Q(...) or %(...) |
| Heredoc equivalent | <<~'TEXT' | <<~TEXT or <<~"TEXT" |
| Suited to | Literal text, Windows paths, text full of backslashes | Text with newlines, tabs, Unicode escapes or embedded values |
In single quotes, 'C:\temp' keeps its backslash because \t is not an escape there, but a backslash at the very end must be doubled ('C:\') so it does not escape the closing quote. Double quotes have two less obvious behaviors. An unrecognized escape such as \q simply yields q, silently dropping the backslash. And interpolation is not limited to #{...}: the shorthand forms #@name, #@@name and #$name also insert instance, class and global variables. Write # when you need a literal # before those characters.
Common escape sequences in double-quoted strings
- \n newline, \t tab, \r carriage return
- \s space, \0 null character
- \e escape character, often used in terminal color codes such as "\e[1m"
- \a bell, \b backspace, \f form feed, \v vertical tab
- \ backslash, " double quote, # literal # (prevents interpolation)
- \nnn octal value, \xnn hexadecimal byte
- \uXXXX Unicode code point with four hex digits, such as \u00e9
- \u{...} one or more code points separated by spaces, such as \u{48 69} for Hi or \u{1F600} for an emoji
- \cx or \C-x control character, \M-x meta character
Percent literals and heredocs
Percent literals let you pick the delimiter, which removes the need to escape quotes. Balanced pairs such as parentheses may nest inside the literal. Heredocs suit multi-line text; the squiggly form <<~ removes the common leading indentation, and quoting the identifier as <<~'TEXT' turns off both interpolation and escapes.
path = %q(C:\Users\dev) # stored as C:\Users\dev
quote = %Q(She said "#{name}") # no need to escape the double quotes
name = "Ada"
message = <<~TEXT
Hello, #{name}.
Your report is ready.
TEXT
template = <<~'TEXT'
Hello, #{name}.
TEXT
# template keeps the characters #{name} literally
Unicode escapes: same appearance, different characters
Two literals can render identically and still hold different characters. An accented e can be written as one precomposed code point or as a plain e followed by a combining accent. They look the same but compare as unequal and have different lengths. This matters for comparison, search and any character-level operation, including reversal: String#reverse works on code points, so a combining mark ends up detached from its letter, while reversing grapheme clusters keeps it attached.
precomposed = "caf\u00e9"
combining = "cafe\u0301"
precomposed == combining # => false
precomposed.length # => 4
combining.length # => 5
combining.unicode_normalize(:nfc) == precomposed # => true
combining.reverse # combining mark moves to the front, detached
combining.grapheme_clusters.reverse.join # keeps the accent on its e
Will the string survive copying and sharing?
- p and inspect print the escaped, quoted form; puts prints the actual characters. Copying puts output loses the distinction between a tab and spaces, or between an ordinary space and a non-breaking one.
- Pasting arbitrary text into double quotes is risky: backslashes are reinterpreted and #{, #@ or #$ sequences trigger interpolation. Single quotes, %q or a quoted heredoc keep pasted text as typed.
- String#dump produces an ASCII-only escaped representation, and String#undump reverses it. This pair is useful when a string must pass through logs or systems that mishandle non-ASCII or control characters.
- JSON escapes overlap with Ruby's but are not identical. JSON writes characters above U+FFFF as two surrogate escapes, whereas Ruby's \u{...} takes the code point directly. Parse JSON with a JSON library rather than pasting JSON-escaped text into a Ruby literal.
- Running code through a shell, as with ruby -e, adds another quoting layer. The shell may consume quotes and backslashes before Ruby sees them.
Readability and accessibility
Escapes help readability in one specific case: invisible or look-alike characters. A zero-width space written as \u200B or a non-breaking space written as \u00A0 is visible in code review, whereas the raw character is not. Beyond that, escapes make text harder to read, translate and edit. How a screen reader voices backslash sequences depends on the tool and its punctuation settings; no assistive technology was tested for this article, so check with the tools your team uses.
When plain text is the better choice
Keep escapes for short strings where exact characters matter, such as protocol strings, terminal codes, test fixtures and invisible characters. For long prose, user-facing messages or content maintained by non-developers, store plain text in a separate file, such as a locale or template file, and load it at runtime. Editors can then read and change the content without knowing Ruby's quoting rules.
Gaps and limits
This review describes documented language behavior and does not include benchmarks or tests of specific editors, terminals or platforms. Some features, such as squiggly heredocs and String#undump, arrived in particular Ruby versions. Confirm behavior against the documentation for the Ruby version you run, especially on older codebases.