%w[ ] Non-interpolated Array of words, separated by whitespace %W[ ] Interpolated Array of words, separated by whitespace
Usage:
p %w{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"] p %W{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"] p %w{C:\ C:\Windows} # => ["C: C:\\Windows"] p %W{C:\ C:\Windows} # => ["C: C:Windows"]
My question is... what's the difference?
%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.
Any constant value which can be assigned to the variable is called as literal/constant. we use literal every time when typing an object in the ruby code. Ruby Literals are same as other programming languages, just a few adjustments, and differences here. These are following literals in Ruby.
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.
%W
treats the strings as double quoted whereas %w
treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Try your arrays again with ruby expressions and you'll see a difference.
EXAMPLE:
myvar = 'one' p %w{#{myvar} two three 1 2 3} # => ["\#{myvar}", "two", "three", "1", "2", "3"] p %W{#{myvar} two three 1 2 3} # => ["one", "two", "three", "1", "2", "3"]
Let's skip the array confusion and talk about interpolation versus none:
irb(main):001:0> [ 'foo\nbar', "foo\nbar" ] => ["foo\\nbar", "foo\nbar"] irb(main):002:0> [ 'foo\wbar', "foo\wbar" ] => ["foo\\wbar", "foowbar"]
The difference in behavior is consistent with how single-quoted versus double-quoted strings behave.
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