ruby - When to use %w? -
the following 2 statements generate same result:
arr = %w(abc def ghi jkl) and
arr = ["abc", "def", "ghi", "jkl"] in cases should %w used?
in case above, want array ["abc", "def", "ghi", "jkl"]. ideal way: former (with %w) or later?
when use %w[...] vs. regular array? i'm sure can think reasons looking @ two, , typing them in, , thinking did.
use %w[...] when have list of single words want turn array. use when have parameters want loop over, or commands know i'll want add in future, because %w[...] makes easy add new elements array. there's less visual noise in definition of array.
use regular array of strings when have elements have embedded white-space trick %w. use arrays have contain elements not strings. enclosing elements inside " , ' intervening commas causes visual-noise, makes possible create arrays object type.
so, pick when use 1 or other when makes sense you. it's called "programmer's choice".
Comments
Post a Comment