What is the difference between %w{} and %W{} upper and lower case percent W array literals in Ruby?

%w[ ]   Non-interpolated Array of words, separated by whitespace
%W[ ]   Interpolated Array of words, separated by whitespace

Usage:

p %w{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]
p %W{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]
p %w{C:\ C:\Windows} # => ["C: C:\\Windows"]
p %W{C:\ C:\Windows} # => ["C: C:Windows"]

My question is... what's the difference?


%W treats the strings as double quoted whereas %w treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Try your arrays again with ruby expressions and you'll see a difference.

EXAMPLE:

myvar = 'one'
p %w{#{myvar} two three 1 2 3} # => ["\#{myvar}", "two", "three", "1", "2", "3"]
p %W{#{myvar} two three 1 2 3} # => ["one", "two", "three", "1", "2", "3"]

Let's skip the array confusion and talk about interpolation versus none:

irb(main):001:0> [ 'foo\nbar', "foo\nbar" ]
=> ["foo\\nbar", "foo\nbar"]
irb(main):002:0> [ 'foo\wbar', "foo\wbar" ]
=> ["foo\\wbar", "foowbar"]

The difference in behavior is consistent with how single-quoted versus double-quoted strings behave.


To demonstrate a case with interpolation and sequence escape for both literals, we assume that:

>> a = 'a'
=> "a"

The lower-case %w percent literal:

>> %w[a#{a} b#{'b'} c\ d \s \']
=> ["a\#{a}", "b\#{'b'}", "c d", "\\s", "\\'"]
  • treats all supplied words in the brackets as single-quoted Strings
  • does not interpolate Strings
  • does not escape sequences
  • escapes only whitespaces by \

The upper-case %W percent literal:

>> %W[a#{a} b#{'b'} c\ d \s \']
=> ["aa", "bb", "c d", " ", "'"]
  • treats all supplied words in the brackets as double-quoted Strings
  • allows String interpolation
  • escapes sequences
  • escapes also whitespaces by \

Source: What is the difference between %w and %W array literals in Ruby