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.
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With