Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby arrays: %w vs %W

Tags:

arrays

ruby

People also ask

What does %w mean Ruby?

%w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.

How do you check if an array contains a value Ruby?

To check if a value is in the array, you can use the built-in include? method. The include? method returns true if the specified value is in the array and false if not.

Are strings arrays in Ruby?

With a Ruby string array, we can store many strings together. We often prefer iterators, not loops, to access an array's individual elements. In Ruby programs, we use string arrays in many places.

What is a literal in Ruby?

A literal is a special syntax in the Ruby language that creates an object of a specific type. For example, 23 is a literal that creates a ​Fixnum object. As for String literals, there are several forms.


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

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

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

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


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


Documentation for Percent Strings: http://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Percent+Strings


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