Elixir is not an object-oriented language, so the module Enum
has only three functions that allow accessing an element of an array based on its index:
iex > Enum.at([:a, :b, :c, :d], 2)
:c
iex > Enum.fetch([:a, :b, :c, :d], 2)
{ :ok, :c }
iex > Enum.fetch!([:a, :b, :c, :d], 2)
{ :ok, :c }
If you try to access non-existent indices, you will get a different result for each function:
iex > Enum.at([:a, :b, :c, :d], 9999)
nil
iex > Enum.fetch([:a, :b, :c, :d], 9999)
:error
iex > Enum.fetch!([:a, :b, :c, :d], 9999)
** (Enum.OutOfBoundsError) out of bounds error
(elixir) lib/enum.ex:722: Enum.fetch!/2
Source: https://til.hashrocket.com/posts/633ba08446-accessing-a-single-element-of-a-list-by-index