Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does %w(array) mean?

I'm looking at the documentation for FileUtils.

I'm confused by the following line:

FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6' 

What does the %w mean? Can you point me to the documentation?

like image 257
Dane O'Connor Avatar asked Aug 13 '09 21:08

Dane O'Connor


People also ask

What is W [] in Ruby?

Ruby provides us with a more elegant solution. The %w syntax is used to create an array of strings without the need for a comma or quotes between each element. Each element will be treated as a string and should be separated by a space. array = %w[1 two 3.4 [] {}]

How do I convert a string to an array in Ruby?

Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.

How can you test if an item is included in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.


2 Answers

I think of %w() as a "word array" - the elements are delimited by spaces and it returns an array of strings.

Here are all % literals:

  • %w() array of strings
  • %r() regular expression.
  • %q() string
  • %x() a shell command (returning the output string)
  • %i() array of symbols (Ruby >= 2.0.0)
  • %s() symbol
  • %() (without letter) shortcut for %Q()

The delimiters ( and ) can be replaced with a lot of variations, like [ and ], |, !, etc.

When using a capital letter %W() you can use string interpolation #{variable}, similar to the " and ' string delimiters. This rule works for all the other % literals as well.

abc = 'a b c' %w[1 2#{abc} d] #=> ["1", "2\#{abc}", "d"] %W[1 2#{abc} d] #=> ["1", "2a b c", "d"] 
like image 29
Mike Woodhouse Avatar answered Oct 12 '22 21:10

Mike Woodhouse


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

like image 128
sepp2k Avatar answered Oct 12 '22 21:10

sepp2k