%w from Ruby for creating string arrays?

Hello!, I'm new to the TC39 Discourse <3

When working with long lists of strings, it may be beneficial to not have to wrap in quotes and type a comma at the end of each string -- especially if you know the strings are "one word".

Ruby has this syntax (or method?) https://stackoverflow.com/questions/690794/ruby-arrays-w-vs-w

where you'd wrap all your words in a single string, and it converts to an array of strings for you.

So, idk if TC39 is the right place to talk about this, or if this is more "standard-lib" territory (would TC39 be the right place for new JS APIs?)

but, I found myself with this on a PR recently to achieve the same behavior

const arrayOfStrings = `
  foo
  bar
  baz
  bax
  etc
`
  .split(/\s/)      // split on whitespace
  .filter(Boolean); // filter out empty strings

I think tagged template literals could achieve the same thing via:

function w(strings) {
  return strings.join().split(/\s/).filter(Boolean);
}

const arrayOfStrings = w`
  foo
  bar
  baz
  bax
  etc
`;

// => Array(5) [ "foo", "bar", "baz", "bax", "etc" ]

idk. what are people's thoughts on this?

Hello and welcome!

Yes, this is a perfect use case for tagged template literals, things like this were the motivation to introduce them. One can and should solve this with a userland library at first, then once it's battle-tested and highly popular in the community it could get adopted into the builtin standard library.

1 Like