When to use% w?

The following two statements will generate the same result:

arr = %w(abc def ghi jkl) 

and

 arr = ["abc", "def", "ghi", "jkl"] 

When should you use %w ?

In the above case, I need an array ["abc", "def", "ghi", "jkl"] . This is the ideal way: first (with %w ) or later?

+4
source share
3 answers

When to use %w[...] against a regular array? I’m sure that you can come up with reasons just by looking at them and then typing them in and thinking about what you just did.

Use %w[...] when you have a list of individual words that you want to turn into an array. I use it when I have parameters that I want to iterate over, or commands that I know. I want to add them in the future because %w[...] makes it easy to add new elements to the array. The array definition has less visual noise.

Use a regular array of strings when you have elements that have an embedded white space that deceives %w . Use it for arrays that should contain elements that are not strings. Closing elements inside " and ' with intermediate commas causes visual noise, but also allows you to create arrays with any type of object.

So, you choose when to use this or that, when it makes the most sense to you. It is called "programmer choice."

+5
source

As you correctly noted, they generate the same result. Therefore, when making a decision, choose the one that produces the simpler code. In this case, this is the %w operator. In the case of your previous question , this is an array literal.

0
source

Using %w avoids the use of quotes around lines.

In addition, there are more such labels:

 %W - double quotes %r - regular expression %q - single-quoted string %Q - double-quoted string %x - shell command 

For more information, see What does% w (array) mean? "

0
source

Source: https://habr.com/ru/post/1480055/


All Articles