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?
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 [] {}]
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.
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.
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"]
%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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With