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

Accepted answer
Score: 83

%W treats the strings as double quoted whereas 4 %w treats them as single quoted (and therefore 3 won’t interpolate expressions or numerous 2 escape sequences). Try your arrays again 1 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"]
Score: 6

Let's skip the array confusion and talk 3 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 2 in behavior is consistent with how single-quoted 1 versus double-quoted strings behave.

Score: 1

To demonstrate a case with interpolation and sequence escape for both 1 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

More Related questions