Percent literals: %w
Ruby provides quite a few percent literals for creating arrays, strings, regular expressions, and more.
The most commonly used percent literal is %w, which creates an array of "words" without needing to quote each string or separate them with commas:
short_list_of_names = %w[Alice Bob Charlie]
# => ["Alice", "Bob", "Charlie"]
long_list_of_names = %w[
Alice
Bob
Charlie
David
Eve
Frank
Grace
Heidi
Ivan
Judy
Karl
Leo
Mallory
Nia
]
# => ["Alice", "Bob", "Charlie", "David", "Eve", ...]
const shortListOfNames = ["Alice", "Bob", "Charlie"];
// => ["Alice", "Bob", "Charlie"]
const longListOfNames = [
"Alice",
"Bob",
"Charlie",
"David",
"Eve",
"Frank",
"Grace",
"Heidi",
"Ivan",
"Judy",
"Karl",
"Leo",
"Mallory",
"Nia",
];
// => ["Alice", "Bob", "Charlie", "David", "Eve", ...]
Note that any whitespace is treated as a separator, so you can format your list of strings horizontally or vertically as you see fit.
Apart from being concise to read and write, I've also found it very convenient when working in IRB sessions to quickly copy and paste a list of words from somewhere else directly into an array. For example, a list of URLs (which don't contain spaces and thus fit the use case perfectly).
When first starting out with Ruby, this shorthand may seem superfluous, but once you get used to it, I guarantee you won't want to live without it.
Which delimiter?
All percent literals in Ruby come in pairs of delimiters. Commonly used ones are %w[], %w(), %w{}, and %w<>. But any non-alphanumeric ASCII character is legal.
The Ruby community has mostly converged on using [] for cases that return arrays, since it mirrors the normal array literal syntax, but don't be surprised if you see other delimiters in the wild.
History
We're continuing to see the influence of Perl on Ruby here. In Perl qw (quote words) is the equivalent of Ruby's %w.
The percent literal syntax may well have been part of Ruby from the very beginning, though I was only able to verify that it was at least present in Ruby 1.4, released in 1999.
In newer languages we can see the Ruby DNA bringing this feature into both Crystal (same syntax as Ruby) and Elixir (via ~w).