case

case accepts an expression, and one or more patterns, which will match against the return value of the expression. These patterns may include guard clauses. These patterns are matched (from top to bottom), and will run the code associated with the first expression that matches. Here is a simple example:

iex> case Enum.random(1..10) do...>   2 -> "The lucky ball was 2"...>   7 -> "The lucky ball was 7"...>   _ -> "The lucky ball was not 2 nor 7"...> end"The lucky ball was not 2 nor 7"

Note that your output may differ when running this example, as we're matching against Enum.random/1. In here, the default condition is represented by using _ in the pattern, which will match anything. Although a bit more condensed, the case construct is similar ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.