Skip to content

Instantly share code, notes, and snippets.

@he9lin
Last active January 8, 2017 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save he9lin/dce76e553da479a9a1c0 to your computer and use it in GitHub Desktop.
Save he9lin/dce76e553da479a9a1c0 to your computer and use it in GitHub Desktop.
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