How to read tuples in Elixir

What is a tuple?

tuples hold numerous elements in a fixed-size container.

tuples are not supported by enum functions.

What is tuple used for?

  1. tuples are used when a function has numerous return values.

  2. They are also used to handle errors.

Syntax

tuple1 = {}

Functions for manipulating tuples

elem/2: This is an index-based access to a tuple.

put elem/3: This adds a value by index into a tuple.

tuple size/1: This is a function that returns the number of elements in a tuple.

An example of how to read a tuple

data_tuple = {"Dib", "Zim", 10, 3.14}
tuple = elem(data_tuple, 0)
IO.inspect tuple
tuple = elem(data_tuple, 2)
IO.inspect tuple

Explanation

From the above example:

  • Line 1: We create a variable and store data inside the tuple.

  • Line 2: We use the elem/2 method (which we explain in the function heading above) to read the data_tuple variable. We also pass an index of the element we want to read. Then, we save it in the tuple variable.

  • Line 3: We use IO.inspect to output our result.

Free Resources