Ruby Arrays: %W VS %W

What does %w(array) mean?

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

Ruby arrays: %w vs %W

%w quotes like single quotes '' (no variable interpolation, fewer escape sequences), while %W quotes like double quotes "".

irb(main):001:0> foo="hello"
=> "hello"
irb(main):002:0> %W(foo bar baz #{foo})
=> ["foo", "bar", "baz", "hello"]
irb(main):003:0> %w(foo bar baz #{foo})
=> ["foo", "bar", "baz", "\#{foo}"]

Ruby %w(...) vs %w[...]

There is no difference. Any single non-alpha-numeric character or any "paired" set of characters can be used as delimiters, as covered in http://en.wikibooks.org/w/index.php?title=Ruby_Programming/Syntax/Literals (see "The % Notation") and http://www.ruby-doc.org/core-2.0.0/doc/syntax/literals_rdoc.html#label-Percent+Strings

What is the difference between %w{} and %W{} upper and lower case percent W array literals in Ruby?

%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"]

What is the difference between %w and %W

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

Using variables with %w or %W - Ruby

%w is not intended to do any splitting, it's a way of expressing that the following string in the source should be split. In essence it's just a short-hand notation.

In the case of %W the #{...} chunks are treated as a single token, any spaces contained within are considered an integral part.

The correct thing to do is this:

words = text.trim.split(/\s+/)

Doing things like %W[#{...}] is just as pointless as "#{...}". If you need something cast as a string, call .to_s. If you need something split call split.

When to use %w?

When to use %w[...] vs. a regular array? I'm sure you can think up reasons simply by looking at the two, and then typing them in, and thinking about what you just did.

Use %w[...] when you have a list of single words you want to turn into an array. I use it when I have parameters I want to loop over, or commands I know I'll want to add to in the future, because %w[...] makes it easy to add new elements to the array. There's less visual noise in the definition of the array.

Use a regular array of strings when you have elements that have embedded white-space that would trick %w. Use it for arrays that have to contain elements that are not strings. Enclosing the elements inside " and ' with intervening commas causes visual-noise, but it also makes it possible to create arrays with any object type.

So, you pick when to use one or the other when it makes the most sense to you. It's called "programmer's choice".

Why do you use %w[] in rails?

This is the most efficient way to define array of strings, because you don't have to use quotes and commas.

%w(abc def xyz)

Instead of

['abc', 'def', 'xyz']

What is the %w thing in ruby?

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.

Why favor the use of %w over ['foo', 'bar']

For three reasons:

  1. %w is more idiomatic ruby

When reading ruby code you will come across %w a lot when dealing with an array of strings. While you can write a simple [] and achieve the same thing %w is the 'ruby way'.


  1. %w conveys more meaning than []

The second and I think more important reason is %w conveys a more specific meaning. An array created with %w can only hold strings, it cannot for example hold integers. So the code is showing its intent clearer to the programmer by pointing out that this array will only ever have strings.


  1. The Ruby philosophy: Multiple ways to do one thing.

Ruby has a philosophy (rightly or wrongly) that the language should give the programmer multiple options to do the same thing so they can do what they think is right. So if you disagree with the rule thats ok :) Here is an snippet from an interview with the creator of Ruby Yukihiro Matsumoto

Ruby inherited the Perl philosophy of having more than one way to do the same thing. I inherited that philosophy from Larry Wall, who is my hero actually. I want to make Ruby users free. I want to give them the freedom to choose. People are different. People choose different criteria. But if there is a better way among many alternatives, I want to encourage that way by making it comfortable. So that's what I've tried to do. Maybe Python code is a bit more readable. Everyone can write the same style of Python code, so it can be easier to read, maybe. But the difference from one person to the next is so big, providing only one way is little help even if you're using Python, I think. I'd rather provide many ways if it's possible, but encourage or guide users to choose a better way if it's possible. - Yukihiro Matsumoto 2003 http://www.artima.com/intv/rubyP.html



Related Topics



Leave a reply



Submit