Ruby's percent literals are shorthand for building strings, arrays, symbols and regular expressions. They are useful in the right places and confusing in the wrong ones, so most style guides set clear limits.
The common forms
| Literal | Produces | Interpolation |
|---|---|---|
%w() | Array of strings | No |
%W() | Array of strings | Yes |
%i() | Array of symbols | No |
%q() | Single quoted style string | No |
%Q() or %() | Double quoted style string | Yes |
%r{} | Regular expression | Yes |
Arrays of words and symbols
Use %w and %i for lists of simple words. They remove the noise of quotes and commas.
STATUSES = %w[pending active suspended].freeze
REQUIRED_FIELDS = %i[name email country].freeze
Switch back to a normal array when an element contains a space or punctuation, because the percent form splits on whitespace and the result becomes hard to read.
Strings with quotes inside
Reach for %() only when a string contains both single and double quotes, such as a snippet of HTML. For everything else a plain quoted string is clearer.
link = %(<a href="#{url}" title='Open'>Details</a>)
Regular expressions with slashes
Use %r when a pattern contains forward slashes, so you avoid escaping each one.
# Hard to read
path_pattern = /\/api\/v\d+\/orders/
# Clearer
path_pattern = %r{/api/v\d+/orders}
Delimiters
Pick one delimiter convention and stick to it. A common choice is square brackets for arrays (%w[], %i[]), braces for regular expressions (%r{}) and parentheses for strings. Consistency matters more than the specific choice.
Forms to avoid
%sfor symbols is rarely clearer than:"some symbol".%xruns a shell command. Prefer backticks or, better,Open3, which gives you control over output and exit status.- Do not use a percent literal just to look clever. If a teammate has to look the syntax up, the plain form was better.