What does ~w means?

Background

I have recently tried Codewars to practice Elixir and I have to admit I am enjoying it quite a lot.
One of the exercises tells me to count vowels. I did my solution and after that I compared it with others. This specific solution baffles me as I don’t quite understand it:

defmodule VowelCount do
  @vowels ~w[a i u e o]
  
  def get_count(str) do
    str
    |> String.graphemes
    |> Enum.count(&(&1 in @vowels))
  end
end

Question

My question here lies in the line @vowels ~w[a i u e o]. I know that @vowels is a constant in the module, but the ~w syntax is complete new to me. What does it mean?

1 Like

It constructs a string list. Saves you the double quotes. Also atom lists.

~w(a b) == ["a", "b"]
~w(a b)a == [:a, :b]
4 Likes

This is a sigil. You can read about them in the getting started guide. This particular sigil is implemented here

3 Likes

~w is a sigil, you can learn more at https://elixir-lang.org/getting-started/sigils.html.

The ~w sigil interpretes the given string as a list of space seperated words:

iex(1)> ~w[a e i o u]
["a", "e", "i", "o", "u"]

They are documented in Kernel, those macros that begin with “sigil_”.

4 Likes

In addition to what others have said, ~w is designed to mimic the behavior of %w from ruby and I believe perl as well. My understanding is that the w stands for word, which is why it splits on whitespace to produce all “words”.

4 Likes