How to get a struct having a value equal to a string combined with a list?

Hi! So basically what I want to do is have the following output: %User{name: "Myfunction(["eat", "bob", "dino"])"}. As can be seen from this, I want a struct which has a string combined with a list as one of its values.

I have tried multiple ways of trying this out, one of which is something like the following:

%User{name: "Myfunction(#{inspect mylist})"}

However, this adds backslashes to the list of words and gives the following output: %User{name: "Myfunction([\"eat\", \"bob\", \"dino\"])"}.

I tried using Enum.join, however, that removes the double quotes from the list of words. I tried traversing over the list and manually adding double quotes at the right places. However, that also adds backslashes.

Is there anyway to get the correct output without having backslashes? And no, I can’t use IO.puts as well.

I have been stuck on this since morning. Can someone please offer their help? Would greatly appreciate it.

this is not valid Elixir. You can’t have (unescaped) " in a (normal) string.

ex(1)> "Myfunction(["eat", "bob", "dino"])"
** (SyntaxError) iex:1:15: syntax error before: eat
iex(2)> ~s(this is a string with "double" quotes, not 'single' ones)
"this is a string with \"double\" quotes, not 'single' ones"

Where do you want to output the string? Only to the console, into a file, onto a website?

Since the string limiter in Elixir is " you have to escape it (with \) when using it in a string (otherwise how would you (or Elixir) known if the " ends the string or is part of it).

If you convert your string to e.g. a charlist the " doesn’t need to be escaped, because the escape character of a charlist is '.

"Myfunction([\"eat\", \"bob\", \"dino\"])" |> to_charlist()
'Myfunction(["eat", "bob", "dino"])'
1 Like

What does exactly the name field represents? Can you modify the struct to follow a different approach?

Something like

 defmodule User do
  defstruct [:name, :arguments]
 end

And try to pattern match on 2 different fields?

%User{name: "Myfunction", arguments: ["eat", "bob", "dino"]} = user