What does %w(array) mean?
Solution 1:
%w(foo bar)
is a shortcut for ["foo", "bar"]
. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.
Solution 2:
I think of %w()
as a "word array" - the elements are delimited by spaces and it returns an array of strings.
Here are all % literals:
-
%w()
array of strings -
%r()
regular expression. -
%q()
string -
%x()
a shell command (returning the output string) -
%i()
array of symbols (Ruby >= 2.0.0) -
%s()
symbol -
%()
(without letter) shortcut for%Q()
The delimiters (
and )
can be replaced with a lot of variations, like [
and ]
, |
, !
, etc.
When using a capital letter %W()
you can use string interpolation #{variable}
, similar to the "
and '
string delimiters. This rule works for all the other % literals as well.
abc = 'a b c'
%w[1 2#{abc} d] #=> ["1", "2\#{abc}", "d"]
%W[1 2#{abc} d] #=> ["1", "2a b c", "d"]
Solution 3:
There is also %s
that allows you to create any symbols, for example:
%s|some words| #Same as :'some words'
%s[other words] #Same as :'other words'
%s_last example_ #Same as :'last example'
Since Ruby 2.0.0 you also have:
%i( a b c ) # => [ :a, :b, :c ]
%i[ a b c ] # => [ :a, :b, :c ]
%i_ a b c _ # => [ :a, :b, :c ]
# etc...
Solution 4:
%W
and %w
allow you to create an Array of strings without using quotes and commas.
Solution 5:
Though it's an old post, the question keep coming up and the answers don't always seem clear to me, so, here's my thoughts:
%w
and %W
are examples of General Delimited Input types, that relate to Arrays. There are other types that include %q
, %Q
, %r
, %x
and %i
.
The difference between the upper and lower case version is that it gives us access to the features of single and double quotes. With single quotes and (lowercase) %w
, we have no code interpolation (#{someCode}
) and a limited range of escape characters that work (\\
, \n
). With double quotes and (uppercase) %W
we do have access to these features.
The delimiter used can be any character, not just the open parenthesis. Play with the examples above to see that in effect.
For a full write up with examples of %w
and the full list, escape characters and delimiters, have a look at "Ruby - %w vs %W – secrets revealed!"