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?
%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.
I think of %w()
as a "word array" - the elements are delimited by spaces.
There are other % literals:
%r()
is another way to write a regular expression. %q()
is another way to write a single-quoted string (and can be multi-line, which is useful) %Q()
gives a double-quoted string %x()
is a shell command %i()
gives an array of symbols (Ruby >= 2.0.0) %s()
turns foo
into a symbol ( :foo
) I don't know any others, but there may be some lurking around in there...
There is also %s
that allows you to create any symbols, for example:
%s|some words| #Same as :'some words'
%s[other words] #Same as :'other words'
%s_last example_ #Same as :'last example'
Since Ruby 2.0.0 you also have:
%i( a b c ) # => [ :a, :b, :c ]
%i[ a b c ] # => [ :a, :b, :c ]
%i_ a b c _ # => [ :a, :b, :c ]
# etc...
链接地址: http://www.djcxy.com/p/10182.html
上一篇: 如何获取字符串在数组中常见的数量
下一篇: %w(数组)是什么意思?