stringelixirstring-interpolation

How do I evaluate or execute string interpolation in Elixir?


Suppose I construct a string using sigil_S:

iex> s = ~S(#{1 + 1})
"\#{1 + 1}"

How do I then get Elixir to evaluate that string or perform interpolation, as if I had entered the literal "#{1 + 1}"?

In other words, how do I get it to evaluate to "2"?

I know I can use EEx instead (e.g. EEx.eval_string "<%=1 + 1%>") but I'm curious if there's a way to do it using just 'plain' string interpolation.


Solution

  • Lower case sigils support interpolation. More about it here:

    If the sigil is lower case (such as sigil_x) then the string argument will allow interpolation. If the sigil is upper case (such as sigil_X) then the string will not be interpolated.

    So, you can use sigil ~s to evaluate interpolation in place:

    ~s(#{1 + 1}) #=> "2"
    ~S(#{1 + 1}) #=> "\#{1 + 1}"
    

    Or you can just simply use string interpolation:

    "#{1 + 1}" #=> "2"
    

    And, finally, if you want to evaluate your code written to a string variable dynamically, you can use Code.eval_string/3:

    s = "\"\#{1 + 1}\""               #=> "\"\#{1 + 1}\""
    s |> Code.eval_string |> elem(0)  #=> "2"