I'm looking at the documentation for Ruby. I'm confused between using %w()
or %W()
(Later W
is upcase). What is the difference between both? Can you point me to some 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.
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.
non-interpolated array of words, separated by whitespace. Used for single-quoted array elements. The syntax is similar to %Q, but single-quoted elements are not subject to expression substitution or escape sequences.
When capitalized, the array is constructed from strings that are interpolated, as would happen in a double-quoted string; when lowercased, it is constructed from strings that are not interpolated, as would happen in a single-quoted string. For example:
irb(main):001:0> foo = "bar"
=> "bar"
irb(main):002:0> %w(#{foo} bar baz)
=> ["\#{foo}", "bar", "baz"]
irb(main):003:0> %W(#{foo} bar baz)
=> ["bar", "bar", "baz"]
irb(main):004:0> ^D
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