Elixir Tuples explained through q&a

This post works best when paired with the Elixir docs for a general overview of Tuples.

What is an Elixir Tuple?

It is a collection data type in Elixir defined using curly brackets `{}`

When should you use a Tuple?

As response objects. The most often take the form of `{:ok, response_data_1, response_data_2}` or `{:error, message}`.

Should you use a Tuple to store a collection of application data you want to iterate over?

No you should use a `List`. Writing and performing operations on a collection in Elixir was designed to be handled using lists.

How do you add an element to an existing Tuple?

One way is to use the `Kernel` `put_elem/3` function. The example below takes a `Tuple`, an index in that `Tuple`, and a new value for that index and creates a new `Tuple`. ``` => put_elem({:ok, "fish", "penguin"}, 1, "lobster") {:ok, "lobster", "penguin"} ```

What happens when you try to use put_elem/3 with a non-existing index?

An `ArgumentError` is raised. ``` => put_elem({:ok, "fish", "penguin"}, 3, "lobster") ** (ArgumentError) argument error ```

How do you retrieve an element from a Tuple without pattern matching?

Using the `Kernel` `elem/2` function and passing it the tuple and the index of the value you want to get. ``` => aqua_friends = {:ok, "fish", "penguin"} => elem(aqua_friends, 1) "fish" ```

How do you retrieve an element from a Tuple through pattern matching?

By using Elixirs match operator `=` to destructure the tuple. See the example below: ``` => {:ok, diet, animal} = {:ok, "fish", "penguin"} => diet "fish" => animal "penguin" ```

How do you remove an element from a Tuple?

Using the `Tuple` `delete_at/2` function and passing it the tuple and the index of the value you want to remove. ``` => Tuple.delete_at({:ok, "lobster", "penguin"}, 2) {:ok, "lobster"} ```

More Elixir Decks:

  1. Atoms and Integers
  2. List