From cccabe496f3361febf045d65f36ff3f3f6cd8016 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 3 Jul 2016 10:10:43 -0500 Subject: [PATCH] Add String Interpolation With Just About Anything as an elixir til --- README.md | 3 ++- ...-interpolation-with-just-about-anything.md | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 elixir/string-interpolation-with-just-about-anything.md diff --git a/README.md b/README.md index 75e8a08..1be07b0 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_443 TILs and counting..._ +_444 TILs and counting..._ --- @@ -89,6 +89,7 @@ _443 TILs and counting..._ - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) - [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md) +- [String Interpolation With Just About Anything](elixir/string-interpolation-with-just-about-anything.md) - [Word Lists For Atoms](elixir/word-lists-for-atoms.md) ### Git diff --git a/elixir/string-interpolation-with-just-about-anything.md b/elixir/string-interpolation-with-just-about-anything.md new file mode 100644 index 0000000..77160bc --- /dev/null +++ b/elixir/string-interpolation-with-just-about-anything.md @@ -0,0 +1,22 @@ +# 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/).