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

Is there a difference between %w(don matt james) and %w[don matt james] in Ruby?

Using the Ruby Console, both of them output an array with each word as an element. I am curious why there are several ways to do this - and how each method should be used.

+7
ruby
source share
3 answers

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

+9
source share

Any option is beautiful and gives the same result. There are even a few additional syntax options:

 %w'don matt james' %w{don matt james} 
+3
source share

In your specific example, the outputs are the same, but there is a difference. The goal of freedom of dividers is to allow other characters within the literal text not to slip away. If you use certain characters as delimiters, you cannot use them inside a notation without escaping. Depending on what you might have, you should use different delimiters.

 ["foo()", "bar()"] %w(foo() bar()) # => error %w[foo() bar()] ["foo[1]", "bar[5]"] %w(foo[1] bar[5]) %w[foo[1] bar[5]] # => error 
0
source share

All Articles