Pattern match in with clause 🤯
Ryan Will
Posted on January 15, 2020
I had a problem where I needed to make sure a string was returned from a function that was part of a with clause. I thought, “You can’t pattern match here, right? That would just be too convenient.”
Turns out you totally can. Here’s an example from the docs.
users = %{"melany" => "guest", "bob" => :admin}
with {:ok, role} when not is_binary(role) <- Map.fetch(users, "bob") do
{:ok, to_string(role)}
end
💖 💪 🙅 🚩
Ryan Will
Posted on January 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.