Is there way I can insert an empty value into a list

I have the following code that creates a list with the data it gets from request.
Data it gets are url, new_url and prefix but sometimes the prefix can be empty.
And after adding it to the list I am dumping it as a CSV.

Problem I am facing is that the CSV for empty prefix is not leaving a field for prefix in the file.

E.g :

PREFIX, URL, NEW_URL
abc, some_url1, new_url1   // with prefix: abc
some_url2, new_url2       // no prefix

What I want

PREFIX, URL, NEW_URL
abc, some_url1, new_url1   // with prefix: abc
, some_url2, new_url2       // no prefix
def add_to_list(new_url, %{url: original_url}, prefix) do
    [~w(#{prefix} #{original_url} #{new_url}) | []]
  end

  def dump_to_csv(list) do
    [~w(PREFIX ORIGINAL_URL NEW_URL)] ++ list
      |> MyParser.dump_to_iodata()
      |> IO.iodata_to_binary
  end

Can you help me here?

It’s not the conversion to csv being the problem here: ~w() splits by whitespace, therefore you’ll get [original_url, new_url] for cases, where prefix is not available. If you use [prefix, original_url, new_url] instead it should work. No need to interpolate variables to a string to then pull out the data again into a list if you can directly create a list with your variables.

3 Likes

Thanks @LostKobrakai
It worked as I expected.