String Delimiters: Because Backslash Escaping Is for Amateurs
2026-02-24
Ruby's % notation mirrors Perl's quoting operators almost exactly. Use any delimiter you want to avoid escaping quotes and slashes. If you've ever written /\/var\/log\/\w+\.log/ and felt your soul leave your body, this post is for you.
Part 1: The Perl to Ruby Quoting Map
| Perl |
Ruby |
Interpolation? |
Purpose |
q~text~ |
%q~text~ |
No |
Single-quoted string |
qq~text~ |
%Q~text~ |
Yes |
Double-quoted string |
qw(a b c) |
%w~a b c~ |
No |
Word array |
qx(cmd) |
%x~cmd~ |
Yes |
Shell command |
m~pattern~ |
%r~pattern~ |
Yes |
Regex |
| N/A |
%i~a b c~ |
No |
Symbol array |
| N/A |
%W~a #{b} c~ |
Yes |
Word array with interpolation |
| N/A |
%I~a #{b} c~ |
Yes |
Symbol array with interpolation |
Part 2: Delimiter Choices
Any non-alphanumeric character works as a delimiter. Paired brackets auto-match:
%Q~Value is:
%Q{Value is:
%Q[Value is:
%Q<Value is:
%Q|Value is:
%Q!Value is:
%Q/Value is:
Preferred style: tildes (~~) to match Perl habits. Your fingers already know the way.
Part 3: String Delimiters
sql = %q~SELECT * FROM users WHERE name = 'O'Brien'~
html = %Q~<div id="main" class='container'>#{content}</div>~
Part 4: Word Arrays and Symbol Arrays
files = %w~config.yml database.yml secrets.yml~
prefix = "app"
dirs = %W~#{prefix}/models
methods = %i~start stop restart status~
Part 5: Regex Delimiters
pattern = %r~https?://[^\s]+~i
url_found = line =~ %r~https?://(\S+)~
path_match = line =~ %r~/var/log/\w+\.log~
Part 6: Shell Commands
output = %x~ls -la /tmp~
disk_usage = %x~df -h /~.chomp
output = `ls -la /tmp`
Part 7: Heredocs, Ruby's Secret Weapon
sql = <<~SQL
SELECT *
FROM users
WHERE status = 'active'
SQL
msg = <<~MSG
Found
Processing took
MSG
template = <<~'TEMPLATE'
Hello
This
TEMPLATE
| Perl |
Ruby |
Notes |
<<END |
<<END or <<~END |
Ruby's ~ strips indentation |
<<'END' |
<<~'END' |
Single-quoted (no interpolation) |
<<"END" |
<<~"END" or <<~END |
Double-quoted (default) |
| Indentation preserved |
<<~ strips leading whitespace |
Ruby wins here |
The squiggly heredoc (<<~) is a genuine Ruby improvement over Perl. It automatically strips the common leading whitespace, so your heredoc content can be indented with your code without the indentation appearing in the output. Once you use it, you'll wonder how you ever lived without it.
Created By: Wildcard Wizard. Copyright 2026