Use of the case Keyword

Learn the use of the case macro in Elixir.

We'll cover the following

The case macro lets us test a value against a set of patterns, executes the code associated with the first pattern that matches, and returns the value of that code. The patterns may include guard clauses.

Example 1

For instance, the File.open function returns a two-element tuple. If the open is successful, it returns {:ok, file}, where file is an identifier for the open file. If the open fails, it returns {:error, reason}. We can use case to take the appropriate action when we open a file. Here, the code opens its own source file.

There’s no need to enter any command for the below codes. Just click the “Run” button and to see the output.

Get hands-on with 1400+ tech skills courses.