1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00
Files
til/elixir/string-interpolation-with-just-about-anything.md

23 lines
935 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# String Interpolation With Just About Anything
Coming to Elixir from Ruby, I am used to being able to interpolate literally
_anything_ into a string. In Elixir, this is not the case.
> By default, it handles strings, atoms (including nil, true, false and
> module name aliases like String which are all just atoms behind the
> scenes), integers, floats, and some lists. That's it.
There are two approaches you can take to interpolate everything else into a
string. The easier approach is to use
[`Kernel.inspect/2`](http://elixir-lang.org/docs/stable/elixir/Kernel.html#inspect/2).
```elixir
> IO.puts "A map #{inspect %{a: 1, b: 2}}"
A map %{a: 1, b: 2}
```
The other approach is to implement the `String.Chars` protocol for the thing
that you are trying to print. You can read more about that in [_Elixir
String Interpolation for
Rubyists_](http://thepugautomatic.com/2016/01/elixir-string-interpolation-for-the-rubyist/).