Ruby arrays: %w vs %W

RubyArrays

Ruby Problem Overview


What is the difference?

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

An application I've found for %W vs %w:

greetings = %W(hi hello #{"how do you do"})
# => ["hi", "hello", "how do you do"]

Solution 3 - Ruby

%W performs normal double quote substitutions. %w does not.

Solution 4 - Ruby

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

Solution 5 - Ruby

Solution 6 - Ruby

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

Solution 7 - Ruby

array = %w(a b c d) 

Same As

array = ["a", "b", "c", "d"]

%w is a short cut symbol for the quotation mark to the string!

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
QuestionAllynView Question on Stackoverflow
Solution 1 - RubyBrian CampbellView Answer on Stackoverflow
Solution 2 - RubyaaandreView Answer on Stackoverflow
Solution 3 - RubyBrianView Answer on Stackoverflow
Solution 4 - RubyMark CView Answer on Stackoverflow
Solution 5 - RubyitsnikolayView Answer on Stackoverflow
Solution 6 - RubyFaruk HossenView Answer on Stackoverflow
Solution 7 - RubyKasem777View Answer on Stackoverflow