Pattern match in with clause 🤯

ryanwilldev

Ryan Will

Posted on January 15, 2020

Pattern match in with clause 🤯

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
💖 💪 🙅 🚩
ryanwilldev
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.

Related

TIL: about Entity Relationship Schemas
TIL IEX Console #2
elixir TIL IEX Console #2

May 12, 2022

Pattern Match Struct's Name
elixir Pattern Match Struct's Name

January 21, 2020

Pattern match in with clause 🤯
elixir Pattern match in with clause 🤯

January 15, 2020