What is the difference?
-
18"%w" is my usual retort to people who get a little too cocky about the readability of Ruby. Works every time. – Craig Stuntz Mar 27 '09 at 17:52
-
now you have an even better response :-) – errata Nov 23 '13 at 09:29
-
6As an irrelevant side note, the URL for this question confused me for a while while the page was loading. – Nic Dec 04 '15 at 19:42
7 Answers
%w quotes like single quotes ''
(no variable interpolation, fewer escape sequences), while %W quotes like double quotes ""
.
irb(main):001:0> foo="hello"
=> "hello"
irb(main):002:0> %W(foo bar baz #{foo})
=> ["foo", "bar", "baz", "hello"]
irb(main):003:0> %w(foo bar baz #{foo})
=> ["foo", "bar", "baz", "\#{foo}"]

- 1,216
- 1
- 13
- 34

- 322,767
- 57
- 360
- 340
-
-
1Yes. When printing output, Ruby always uses double quotes and escapes characters like `#`. `'#{foo}'` and `"\#{foo}"` give you the same string, which you can verify with `'#{foo}' == "\#{foo}"` in `irb`. – Brian Campbell Dec 04 '16 at 05:37
-
An application I've found for %W vs %w:
greetings = %W(hi hello #{"how do you do"})
# => ["hi", "hello", "how do you do"]

- 2,502
- 5
- 33
- 46
-
12Although in this case, it's prob easier to just do `greetings = %w(hi hello how\ do\ you\ do)` – dinjas Feb 11 '14 at 23:17
Though 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 upper and lower case is that it gives us access to the features of single and double quote. With single quotes and lowercase %w, we have no code interpolation (e.g. #{someCode} ) and a limited range of escape characters that work (e.g. \, \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: http://cyreath.blogspot.com/2014/05/ruby-w-vs-w-secrets-revealed.html
Mark

- 615
- 9
- 15
-
1That's a good article. I didn't realize you can make strings or other things the same way and the enclosing characters can be whatever you want. For example, `%w&readable af&` – Dex Jun 29 '19 at 07:03
Documentation for Percent Strings: http://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Percent+Strings

- 17,415
- 4
- 65
- 64
%W
is used for double-quoted array elements like %Q
, for example,
foo = "!"
%W{hello world #{foo}} # => ["hello", "world", "!"]
%w
is used for single-quoted array elements like %q
.
%w(hello world #{foo})
# => ["hello","world", "\#{foo}"]

- 3,003
- 1
- 17
- 29

- 185
- 1
- 8