May 2018
Intermediate to advanced
412 pages
9h 3m
English
case lets you 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.
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. (Here, the code opens its own source file.)
| | 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 ...
Read now
Unlock full access