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

Ruby

Ruby Problem Overview


%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?

Ruby Solutions


Solution 1 - Ruby

%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"]

Solution 2 - Ruby

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.

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanScottLewisView Question on Stackoverflow
Solution 1 - RubyacconradView Answer on Stackoverflow
Solution 2 - RubyPhrogzView Answer on Stackoverflow
Solution 3 - RubyaloucasView Answer on Stackoverflow