Last active
January 8, 2017 04:37
-
-
Save he9lin/dce76e553da479a9a1c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Interpolation do | |
def call(string, bindings \\ []) do | |
~r/(?<head>)%{[^}]+}(?<tail>)/ | |
|> Regex.split(string, on: [:head, :tail]) | |
|> Enum.reduce("", fn | |
<<"%{" <> rest>>, acc -> | |
key = String.to_atom(String.rstrip(rest, ?})) | |
acc <> to_string(Dict.fetch!(bindings, key)) | |
segment, acc -> | |
acc <> segment | |
end) | |
end | |
end | |
"Hello, world" | |
|> Interpolation.call | |
|> IO.puts | |
"Hello, %{first} %{last}" | |
|> Interpolation.call(first: "Lin", last: "He") | |
|> IO.puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment