Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Ruby array of words

I was just working with array of words in ruby which I usually write like this:

%w(a b c)
#=> ["a", "b", "c"]

And I came across a post in which I saw author using %w|| instead of %w(). And then out of curiosity I tried following:

%w|a b c|
#=> ["a", "b", "c"]

%w_a b c_
#=> ["a", "b", "c"]

%w*a b c*
#=> ["a", "b", "c"]

%w-a b c-
#=> ["a", "b", "c"]

%w+a b c+
#=> ["a", "b", "c"]

Also, same happened with array of symbols

%i|a b c|
#=> [:a, :b, :c]

%i_a b c_
#=> [:a, :b, :c]

%i*a b c*
#=> [:a, :b, :c]

%i-a b c-
#=> [:a, :b, :c]

%i+a b c+
#=> [:a, :b, :c]

Is it something which is done intentionally?

Is there any difference in these formats or it's just for the convenience of programmers.

Upvotes: 1

Views: 665

Answers (2)

tessi
tessi

Reputation: 13574

This is done intentionally by the language designers so you can have arbitrary strings in your array. The syntax even considers certain "opening" vs. "closing" symbols as delimiters:

If you are using “(”, “[”, “{”, “<” you must close it with “)”, “]”, “}”, “>” respectively. You may use most other non-alphanumeric characters for percent string delimiters such as “%”, “|”, “^”, etc.

You can read more about it in the language documentation.

Upvotes: 3

Eric Duminil
Eric Duminil

Reputation: 54233

It makes it possible to input :

%w|a) b) c)|
#=> ["a)", "b)", "c)"]

In contrast :

%w(a) b) c))

is a SyntaxError :

SyntaxError: unexpected tIDENTIFIER, expecting end-of-input

It also works for strings :

%q|"](\/#{t}'?}|
#=> "\"](\\/\#{t}'?}"

Upvotes: 12

Related Questions