Question
I was reading the Ruby FileUtils documentation and saw this line:
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
I am confused about the %w(...) part.
What does %w mean in Ruby, and where can I find the documentation for it?
Short Answer
By the end of this page, you will understand that %w(...) is Ruby shorthand for creating an array of strings. You will see how it works, why it is useful, how it differs from normal array syntax, and when to use %w versus other similar Ruby literals.
Concept
In Ruby, %w(...) is a special literal syntax for creating an array of strings.
This line:
%w(cgi.rb complex.rb date.rb)
is roughly the same as writing:
["cgi.rb", "complex.rb", "date.rb"]
Ruby splits the contents inside %w(...) by whitespace and turns each item into a string.
So this code:
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
means:
FileUtils.cp(["cgi.rb", "complex.rb", "date.rb"], '/usr/lib/ruby/1.6')
Why Ruby has this syntax
Ruby includes several literal shortcuts to make common code shorter and easier to read. %w is useful when:
- you need a list of simple strings
- the strings do not need interpolation
- you want to avoid typing lots of quotes and commas
For example, this:
%w(red green blue)
is faster to write and often easier to scan than this:
["red", "green", "blue"]
Important rule
%w creates plain strings only. It does not evaluate variables or string interpolation.
Example:
name = "Ruby"
p %w(hello #{name})
Output:
["hello", "\#{name}"]
If you want interpolation, Ruby provides %W(...) with a capital W instead.
Mental Model
Think of %w(...) as a quick packing list.
Instead of writing each label separately with quotes and commas:
["shirt", "shoes", "hat"]
you give Ruby one space-separated list:
%w(shirt shoes hat)
Ruby reads the list, splits it at spaces, and packs each word into its own string.
So %w(...) is like saying:
- "Here is a list of words"
- "Please turn each one into a string"
- "Put them all into an array"
Syntax and Examples
Basic syntax
%w(item1 item2 item3)
This creates an array of strings:
["item1", "item2", "item3"]
Example 1: Simple list
files = %w(cgi.rb complex.rb date.rb)
p files
Output:
["cgi.rb", "complex.rb", "date.rb"]
Example 2: Equivalent normal syntax
files = ["cgi.rb", "complex.rb", "date.rb"]
This is functionally the same as:
files = %w(cgi.rb complex.rb date.rb)
Example 3: Different delimiters
Ruby lets you use delimiters other than parentheses.
%w[apple banana orange]
%w|apple banana orange|
%w{apple banana orange}
These all create the same result.
Example 4: Escaping spaces
If one item itself contains a space, escape it:
p %w(New\ York Los\ Angeles Chicago)
Output:
["New York", "Los Angeles", "Chicago"]
Example 5: No interpolation with %w
language = "Ruby"
p %w(I like #{language})
Output:
["I", "like", "\#{language}"]
If you need interpolation:
language = "Ruby"
p %W(I like #{language})
Output:
["I", "like", "Ruby"]
Step by Step Execution
Consider this code:
files = %w(cgi.rb complex.rb date.rb)
p files
Here is what happens step by step:
- Ruby sees
%w(...)and recognizes it as an array-of-strings literal. - Ruby reads the contents inside the delimiters:
cgi.rbcomplex.rbdate.rb
- Ruby splits the contents on whitespace.
- Each piece becomes a string.
- Ruby builds the array:
["cgi.rb", "complex.rb", "date.rb"]
- The variable
filesnow refers to that array. p filesprints the array.
Now apply that to the original example:
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
Ruby evaluates %w(cgi.rb complex.rb date.rb) first, producing:
["cgi.rb", "complex.rb", "date.rb"]
Then it calls FileUtils.cp with:
- the source files array
- the destination directory string
So it behaves like:
FileUtils.cp(["cgi.rb", "complex.rb", "date.rb"], "/usr/lib/ruby/1.6")
Real World Use Cases
%w appears often in real Ruby code when developers need a short list of fixed strings.
Common examples
File names
files = %w(app.rb config.rb Gemfile)
Allowed values
VALID_STATUSES = %w(pending active archived)
Command-line options
flags = %w(--help --version --verbose)
Model attributes or keys
fields = %w(name email role)
Test data
users = %w(alice bob charlie)
Why developers use it
- less punctuation to type
- easier to scan visually
- good for fixed lists of simple string values
- common in configuration-style Ruby code
Real Codebase Usage
In real projects, %w is usually used for static lists that are known ahead of time.
Common patterns
Constants
ALLOWED_EXTENSIONS = %w(.jpg .png .gif)
This is common when validating user input.
Guard clauses
def valid_role?(role)
return false unless %w(admin editor viewer).include?(role)
true
end
A fixed list of allowed values is easy to read with %w.
Filtering
visible_columns = %w(name email created_at)
records.map { |record| record.slice(*visible_columns) }
Configuration
ignored_dirs = %w(tmp log node_modules)
Test suites
%w(GET POST PUT DELETE).each do |method|
puts "Testing #{method}"
end
When teams avoid it
Developers may avoid %w when:
- strings contain lots of spaces
- interpolation is needed
- explicit quoting would be clearer
- special characters make escaping messy
In those cases, normal array syntax may be easier to maintain.
Common Mistakes
1. Expecting interpolation to work
Broken example:
name = "Ruby"
p %w(hello #{name})
This does not produce "Ruby".
Result:
["hello", "\#{name}"]
Use %W instead:
name = "Ruby"
p %W(hello #{name})
2. Forgetting that spaces split items
Broken example:
cities = %w(New York London)
Result:
["New", "York", "London"]
If you want "New York" as one item, escape the space:
cities = %w(New\ York London)
3. Using %w for strings that need quotes or special formatting
Sometimes normal arrays are clearer:
messages = ["hello world", "good bye", "see you later"]
This may be more readable than escaping many spaces.
4. Assuming %w is a method call
%w is not a regular method like Array.new. It is a Ruby literal syntax built into the language.
5. Not recognizing alternate delimiters
These are valid:
%w(a b c)
%w[a b c]
%w|a b c|
Beginners sometimes think only parentheses work.
Comparisons
%w compared with related Ruby syntax
| Syntax | Purpose | Interpolation? | Best for |
|---|---|---|---|
%w(a b c) | Array of strings | No | Simple fixed string lists |
%W(a b #{x}) | Array of strings | Yes | Lists that include variables or escapes |
["a", "b", "c"] | Normal array syntax | Yes, inside double-quoted strings | General-purpose arrays |
%i(one two three) | Array of symbols | No | Lists of symbols |
['a', 'b', 'c'] | Normal array with single-quoted strings | No interpolation | Explicit string arrays |
%w vs normal array syntax
%w(red green blue)
vs
["red", "green", "blue"]
Use %w when:
- all items are simple strings
- you want shorter syntax
- no interpolation is needed
Use normal array syntax when:
- strings contain spaces often
- you need mixed value types
- explicit quoting improves readability
%w vs %W
name = "Ruby"
p %w(hello #{name})
p %W(hello #{name})
Output:
["hello", "\#{name}"]
["hello", "Ruby"]
Cheat Sheet
Quick reference
Create an array of strings
%w(a b c)
# => ["a", "b", "c"]
Equivalent syntax
["a", "b", "c"]
Different delimiters
%w(a b c)
%w[a b c]
%w{a b c}
%w|a b c|
Interpolation
%w(hello #{name}) # no interpolation
%W(hello #{name}) # interpolation works
Spaces inside one item
%w(New\ York Los\ Angeles)
# => ["New York", "Los Angeles"]
Best use case
- short, fixed lists of plain strings
Avoid when
- strings contain many spaces
- you need variables inside strings
- readability is better with explicit quotes
Documentation hint
Look up Ruby's percent string literals or Array literals with %w / %W in the Ruby language documentation.
FAQ
Where is %w documented in Ruby?
It is documented as part of Ruby's percent-literal syntax, often described under string and array literals. Search for Ruby %w or Ruby percent literals in the official syntax documentation.
Is %w the same as an array?
It creates an array, specifically an array of strings.
Can %w contain numbers?
Yes, but they become strings:
%w(1 2 3)
# => ["1", "2", "3"]
What is the difference between %w and %W in Ruby?
%w does not process interpolation. %W does.
Can I use commas inside %w?
You usually separate items with spaces, not commas. If you include commas, they become part of the strings.
%w(a,b,c)
# => ["a,b,c"]
Why do Ruby developers use %w?
Because it is concise and readable for simple lists of fixed strings.
Is %w only used with files?
No. It can be used for any array of simple strings, such as names, statuses, commands, or keys.
Mini Project
Description
Build a small Ruby script that groups file names by type using %w arrays. This demonstrates how %w is used for fixed lists of strings in a realistic script, similar to configuration or file-processing code.
Goal
Create a script that defines groups of file names with %w, then prints each group and the total number of files.
Requirements
- Create at least two arrays using
%w(...) - Store file names as strings inside those arrays
- Print each array with a label
- Print the number of files in each group
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.