Home / Womply Ruby Style Guide

Ruby Percent Literals: When to Use %w, %i, %q and Friends

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

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

LiteralProducesInterpolation
%w()Array of stringsNo
%W()Array of stringsYes
%i()Array of symbolsNo
%q()Single quoted style stringNo
%Q() or %()Double quoted style stringYes
%r{}Regular expressionYes

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

More on Womply Ruby Style Guide

Explore the archive