O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

case

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

For example, 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. (In this case the code opens its own source file.)

control/case.ex
 
case​ File.open(​"case.ex"​) ​do
 
{ :ok, file } ->
 
IO.puts ​"First line: #{IO.read(file, :line)}"
 
{ :error, reason } ->
 
IO.puts ​"Failed to open file: #{reason}"
 
end

produces:

 
First line: case File.open("case.ex") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required