Interpolation Operator #{}

The interpolation operator in Elixir, represented as #{}, is a powerful tool used for inserting values within a string. It allows for dynamic expression of values within a string without the need for explicit concatenation. Here’s a simple example:

iex> name = "Alice"
"Alice"
iex> "Hello, #{name}"
"Hello, Alice"

In the example above, the variable name is interpolated into the string. The resulting string is "Hello, Alice".

String interpolation in Elixir can handle more complex expressions, not just variables. This includes arithmetic operations, function calls, and more:

iex> number = 5
5
iex> "The square of #{number} is #{number * number}"
"The square of 5 is 25"

In the above code, the expressions inside the interpolation operator #{} are evaluated, and their results are automatically converted into strings and inserted in the appropriate place.

Another powerful aspect of string interpolation in Elixir is that it’s not restricted to strings. It works with any value that implements the String.Chars protocol, including integers, floats, atoms, booleans, and binaries.

iex> list = [1, 2, 3]
[1, 2, 3]
iex> "The list is #{inspect(list)}"
"The list is [1, 2, 3]"

Complex types such as tuples, maps, and regular lists do not implement String.Chars, so interpolating them directly raises Protocol.UndefinedError:

iex> tuple = {1, 2, 3}
{1, 2, 3}
iex> "The tuple is #{tuple}"
** (Protocol.UndefinedError) protocol String.Chars not implemented for Tuple

To embed those values, pipe them through Kernel.inspect/1 first (as with the list above), which always produces a string.

Remember, the expressions inside the interpolation operator #{} must be valid Elixir expressions.

The #{} operator itself can’t be used outside a string, as it’s a part of the string syntax, not a standalone operator.