Skip to content

Instantly share code, notes, and snippets.

@zporter
Created September 12, 2018 10:08
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 zporter/1c31d4181c370c5fe09d3e66c574add5 to your computer and use it in GitHub Desktop.
Save zporter/1c31d4181c370c5fe09d3e66c574add5 to your computer and use it in GitHub Desktop.
Elixir: Parsing initials of a given name
iex(2)> c "name.ex"
[Name]
iex(3)> Name.initials("Cher")
"C"
iex(4)> Name.initials("Barry Bluejeans")
"BB"
iex(5)> Name.initials("Jean-Claude Van Damme")
"JVD"
defmodule Name do
def initials(name) when name in [nil, ""], do: "?"
def initials(name) when is_binary(name) do
name
|> String.split(" ")
|> extract_initials()
end
defp extract_initials([]), do: ""
defp extract_initials([name_part | name_parts]) do
String.slice(name_part, 0, 1) <> extract_initials(name_parts)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment