I\'m referring to the %w operator/constructor/whatever you may call it, used like this:
%w{ foo bar baz }
=> [\"foo\", \"bar\", \"baz\"]
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/
Not actually sure, string encoded literals I guess.
Nope. You can use almost any character actually. If you start with a {
, [
or (
you need to close with the closing counterpart of that character, but other characters are closed with the same character. You probably want to use a character that is not going to appear inside your literal.
%w_ foo bar _
Not one for an array of symbols, but there is a %q
for a single quoted string, %Q
for a double quoted string, %r
for a regex, and probably a few other as well I am forgetting.
Nope. They are for quick and easy ways to create simple objects. If you need nesting, you need to use the more verbose syntax.
1) It is a litteral, where it is a %
then a r(regular expression), w(array), q(string) etc to denote different litterals.
2)
ruby-1.9.2-p136 :001 > %w{1 2 3}
=> ["1", "2", "3"]
ruby-1.9.2-p136 :002 > %w[1 2 3]
=> ["1", "2", "3"]
ruby-1.9.2-p136 :008 > %w!a s d f!
=> ["a", "s", "d", "f"]
ruby-1.9.2-p136 :009 > %w@a s d f@
=> ["a", "s", "d", "f"]
So you can see that you can use any charater as long as it marks both the beginning and end of the content.
3)
Here are some other examples:
Strings:(%q or %Q)
ruby-1.9.2-p136 :016 > %Q[ruby is cool]
=> "ruby is cool"
ruby-1.9.2-p136 :017 > %q[ruby is "cool"]
=> "ruby is \"cool\""
Regex: (%r)
ruby-1.9.2-p136 :019 > %r[(\w+)]
=> /(\w+)/
Sys command: (%x)
ruby-1.9.2-p136 :020 > %x[date]
=> "Tue Mar 29 12:55:30 EDT 2011\n"
4) 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:
ruby-1.9.2-p136 :003 > %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:
ruby-1.9.2-p136 :011 > [1, [2,3,4], 5]
=> [1, [2, 3, 4], 5]
Unsure about the "official" documentation but this is pretty good : http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation
Whether you use {} [] () or <> does not matter except if your string contains this character e.g.:
%q{a closing parenthesis: ")"}
The syntax is pretty complex so remembering every variant is not very useful, but it can come in handy when you are hacking quickly and want to avoid taking care of escape characters manually.