Getting started with Elixir.

  • Install Elixir
  • Play in IEx to experiment.
  • Execute a Script File.
  • How to get started with the Elixir language.
  • Where to Next?

Install Elixir

Follow the installation steps for your platform on the official Elixir website.

I’m using Arch Linux, so that’s what I’ll do now.

Note: Installing Elixir will automatically install the Erlang dependency.

sudo pacman -S elixir

Wow, that was easy! At this point we can run IEx. Try it out.

Running Commands in the Interactive Shell (IEx)

$ iex
Erlang/OTP 18 [erts-7.1] [source] [64-bit] [smp:3:3] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.1.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

Enter your first Elixir code with a “Hello World” example. Enter ‘IO.puts “Hello World”’.

iex(1)> IO.puts "Hello World"
Hello World
:ok
iex(2)>

Don’t worry about the “iex(2)” prompt. The number is showing the line number and it isn’t significant.

To exit the shell, enter CTRL+C two times.

Execute a Script File

The following create a module called “SayingHello” with a single function called “say_it”. After defining the module, we call the function.

Using your editor of choice, save this code to a file called “saying_hello.exs”.

defmodule SayingHello do
  def say_it do
    IO.puts "Hello!"
  end
end

SayingHello.say_it()

Running this script file from the command line.

$ elixir saying_hello.exs
Hello!

It runs immediately, performs the task and exits.

We can also copy and paste the module definition into IEx and play with it there.

Copy the following…

defmodule SayingHello do
  def say_it do
    IO.puts "Hello!"
  end
end

… paste it into IEx

iex(1)> defmodule SayingHello do
...(1)>   def say_it do
...(1)>     IO.puts "Hello!"
...(1)>   end
...(1)> end
{:module, SayingHello,
 <<70, 79, 82, 49, 0, 0, 4, 208, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 129, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
 {:say_it, 0}}
iex(2)>  

Now at the prompt, type “Say” and press TAB. It will auto-complete to “SayingHello.”. Press “say” and TAB again to complete the rest. Hitting “enter” will execute the command.

iex(2)> SayingHello.say_it
Hello!
:ok
iex(3)>  

Getting Started with the Language

This is enough to get an environment setup that run Elixir commands. Refer to the official documentation for learning about how the language works.

There are books available and websites for exercises to work on.

The Elixir website’s “Learning” section lists some of these resources.

Next Step…

Elixir is really cool. While IEx is awesome. It isn’t a great place to really play and dig into the language. Next we’ll cover getting started with an Elixir “mix”.