Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 631
RyanScottLewis Avatar asked Apr 22 '11 02:04

RyanScottLewis


People also ask

What is W {} in 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. You can find a list of ways of writing literals in zenspider's quickref.

What are literals in Ruby?

Any constant value which can be assigned to the variable is called as literal/constant. we use literal every time when typing an object in the ruby code. Ruby Literals are same as other programming languages, just a few adjustments, and differences here. These are following literals in Ruby.

What is %q in Ruby?

Alternate double quotes The %Q operator (notice the case of Q in %Q ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the %q operator.


2 Answers

%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"] 
like image 102
acconrad Avatar answered Oct 22 '22 02:10

acconrad


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.

like image 27
Phrogz Avatar answered Oct 22 '22 03:10

Phrogz