Reading Values from a Tuple

Essential Elixir : part 1 of 10 published on Jun 09, 2015

Tuples are a basic data type in Elixir. When you first encounter a tuple, you could run into some difficulties getting the data out. But don’t worry, we will cover some basic, painless ways of getting the data you want out.

Here is the tuple we will be trying to read values out of. Our goal is to get the status, quote, and author.

message = { :ok, "To improve is to change; to be perfect is to change often.", author: "Winston Churchill" }
status = ?
message = ?
author = ?

Whats with the :ok? Many library function calls return some form of status message as first parameter of the resulting tuple. Might as well practice with something that you will encounter on your journeys with Elixir.

elem

If you know the index of the element you want, you can use the elem function to retrieve the value.

message = { :ok, "To improve is to change; to be perfect is to change often.", author: "Winston Churchill" }
# use the elem function to read values from a tuple
status = elem(message, 0)
message = elem(message, 1)
author = elem(message, 2)[:author]

Pattern Matching

You can also use pattern matching to retrieve the values from the Tuple.

message = { :ok, "To improve is to change; to be perfect is to change often.", author: "Winston Churchill" }
# set the values on status, message, and author with pattern matching
{ status, message, author: author } = message

But suppose you just wanted the author and you didn’t care about any of the other values. We can still use pattern matching but just tell Elixir to ignore the other values.

message = { :ok, "To improve is to change; to be perfect is to change often.", author: "Winston Churchill" }
# only set the value on author with pattern matching
{ _, _, author: author } = message
Next: Elixir's version of the ternary operator