Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
Alistair A. Israel Avatar asked Feb 07 '23 03:02

Alistair A. Israel


2 Answers

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"
like image 77
Vitalii Elenhaupt Avatar answered Feb 09 '23 06:02

Vitalii Elenhaupt


You should be able to use the Code module which has the function eval_string so just swap out EEx for Code

Code.eval_string "1 + 1"
like image 38
PaReeOhNos Avatar answered Feb 09 '23 07:02

PaReeOhNos