Wednesday, May 14, 2014

%w

What is the %w “thing” in ruby?

%w means white space divided array


It is a literal, where it is a % then a r(regular expression), w(array), q(string) etc to denote different literals.

$   %w{1 2 3}
 => ["1", "2", "3"]

$   %w[1 2 3]
 => ["1", "2", "3"]

$ %w!a s d f!
 => ["a", "s", "d", "f"]

$ %w@a s d f@
 => ["a", "s", "d", "f"]

So you can see that you can use any character as long as it marks both the beginning and end of the content.

Here are some other examples:



Strings:
(%q or %Q)
$ %Q[ruby is cool]
 => "ruby is cool"

$ %q[ruby is "cool"]
 => "ruby is \"cool\""

Regex: (%r)
$ %r[(\w+)]
 => /(\w+)/

Sys command: (%x)
$ %x[date]
 => "Tue Mar 29 12:55:30 EDT 2011\n"

They cannot be nested because the %w means white space divided array. So if you try to do multi-level, it would look like this:

$ %w{1 %w{2 3 4} 5}
 => ["1", "%w{2", "3", "4}", "5"]
To accomplish this, you would need to use the more verbose syntax:
$ [1, [2,3,4], 5]
 => [1, [2, 3, 4], 5]

There are various forms of literal syntax you can use, with pretty much any paired delimiter, see http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html:

%w[one two three] # == ["one", "two", "three"]
%[one two three] # == "one two three"
%[one "two" three] # == "one \"two\" three"
%r[one two three] # == /one two three/