Question

What are the right situations to use %w:

percent_notation = %w(first second third)
explicit = ["first", "second", "third"]

for creation of arrays? With arrays of size 501, the difference in creation time is approx. .04 milliseconds. Is this a significant difference that would cause us to use the explicit over the percent notation?

Besides being quicker to write, are there any reasons to use one or the other? Does proper ruby style ask for one version over the other?

Était-ce utile?

La solution

You are over-thinking the problem.

I use %w when it is easier than writing a regular array definition, or more visually distinct.

It's a programmer's choice and often comes down to the question: Which is easier to maintain?

When defining single words it makes a lot more sense to use %w:

ary = %w[a b c foo bar]

Than it does to use:

ary = ['a', 'b', 'c', 'foo', 'bar']

However, if you have embedded spaces you need to maintain it becomes more readable to use a normal array definition:

ary = ['a b c', 'foo bar']

Compared to:

ary = %w[a\ b\ c foo\ bar]

As I tell my team during code reviews, look at the code as you write it and observe the work your brain does to decipher it. Go with whichever flows in easier and is easier to maintain code-wise. We write it once but it might get maintained many times, so make it easier for those who follow us.

There is absolutely no difference in creation time for the array definitions. Both would be parsed as Ruby starts its interpretation of the code and only then. Even if there was a difference, you couldn't measure it with a benchmark and it would occur once so what difference would it make over the run-time of the script?

Autres conseils

If you're a code golfer, it's shorter in terms of characters. But it's much less readable and if you develop in a team, chances are you're forcing other developers to waste time by having to look up what it does.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top