Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between %w and %W

Tags:

arrays

ruby

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?

like image 781
Bhushan Lodha Avatar asked Jan 25 '12 02:01

Bhushan Lodha


People also ask

What does %w mean in a string?

%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.

What is %q 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.

What is non interpolated array?

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.


1 Answers

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
like image 74
mipadi Avatar answered Oct 19 '22 11:10

mipadi