I'm referring to the %w operator/constructor/whatever you may call it, used like this:
%w{ foo bar baz }
=> ["foo", "bar", "baz"]
I have several questions about it:
%w
"thing"? Operator? Literal? Constructor?{}
s instead of []
s?%w
inside another %w
, in order to create nested arrays)?%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.
%w[hello billing confirmation] is syntax sugar for ["hello", "billing", "confirmation"] . It tells Ruby to break up the input string into words, based on the whitespace, and to return an array of the words.
i know that the '?' in ruby is something that checks the yes/no fulfillment.
Alternate double quotes The %Q operator (notice the case of Q in %Q ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the %q operator.
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]
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