Elixir Language Pattern matching Tuples


Example

{ a, b, c } = { "Hello", "World", "!" }    

IO.puts a # Hello
IO.puts b # World
IO.puts c # !

# Tuples of different size won't match:

{ a, b, c } = { "Hello", "World" } # (MatchError) no match of right hand side value: { "Hello", "World" }

Reading a File

Pattern matching is useful for an operation like file reading which returns a tuple.

If the file sample.txt contains This is a sample text, then:

{ :ok, file } = File.read("sample.txt")
# => {:ok, "This is a sample text"}

file
# => "This is a sample text"

Otherwise, if the file does not exist:

{ :ok, file } = File.read("sample.txt")
# => ** (MatchError) no match of right hand side value: {:error, :enoent}

{ :error, msg } = File.read("sample.txt")
# => {:error, :enoent}