user483040
user483040

Reputation:

String.to_atom resulting in and atom with double quotes buried in it

I've got this code where I using a pair of lists to get a map with one list being the keys and the other list being the values. Pretty straight forward code:

defp create_data_map(columns, row) do
  Enum.zip(columns, row)
  |> Enum.into(%{}, fn {k, v} ->
    {String.to_atom(k), v}
  end)
end

I'm getting these lists from a csv file where columns is the first line, which is the list of headers, and the second line is any one of the lines after that. Here is what the header looks like:

["action", "source_application", "partner_name", "detail", "college_name",
 "ipeds_id", "deleted", "deleted_at", "athlete_id", "athlete_email",
 "athlete_first_name", "athlete_last_name", "athlete_sport_id",
 "athlete_sport_name", "pass_uuid", "coach_id", "coach_id", 
 "coach_email",
 "coach_first_name", "coach_last_name", "coach_position", "coach_sport_id",
 "coach_sport_name", "occurred_at"]

For some reason, the 'action' key, after calling String.to_atom/1 ends up being :"action". None of the other keys have that issue. They are all correctly formed atoms.

I don't see what's different about that action key from the other keys, aside from the fact that it's at the start of the list.

Upvotes: 2

Views: 1335

Answers (2)

Mohit Israni
Mohit Israni

Reputation: 11

There are 3 different ways an Atom can appear when converted using String.to_atom()

  1. :"Atom-" or :"atom-"
  2. :Atom or :atom
  3. Atom

All the 3 above are atoms. The only difference in them is the way the strings are formatted.

  1. First one is obtained for any usual string that also contains special characters like #$%- ...
    iex> "Atom-" |> String.to_atom
    :"Atom-"
  2. Then similar to how functions names are subtly formatted in elixir. i.e. the string starts with an alphabet and the remaining string can only contain alphabets, numbers, or the three special characters _!@ .
    iex> "Atom" |> String.to_atom
    :Atom

  3. Third again in the same way as Modules are named subtly in Elixir. Since internally, module names are just atoms as well. The String should start with Elixir. followed by a capital letter and can contain only alphabets.
    iex> "Elixir.Atom" |> String.to_atom
    Atom​​​


Module Names: Elixir, Erlang, and Atoms

Understanding Aliases

Upvotes: 1

narrowtux
narrowtux

Reputation: 703

When inspect/1 renders your atom as :"hello world", the name of the atom contains characters like whitespace, dots or uppercase letters.

See how you would not be able to reference the above atom as :hello world, because it would interpret world as a variable.

They are still valid atoms, though it might be harder to use them in your code.

Upvotes: 1

Related Questions