Elixir Debugging Techniques

May 16, 2017

Elixir Debugging Techniques

Coming to Elixir from Ruby, one of the things I missed most was a tool like pry.

Elixir basics

Pry is a Ruby tool that you start a debugging session that enables you to see what state the program was in. I could see what values variables were initialized to and call object methods that were in the current scope.

Fortunately, Elixir provides a tool like that out of the box with IEx. Here’s how you use it.

Step 1 – require IEx

First, you have to require IEx in your program. The following is a sample usage.

defmodule RunLengthEncoder do
  @encoder [] # use keyword list instead of map

  @spec encode(String.t) :: String.t
  def encode(string) do
    require IEx; IEx.pry
    String.split(string,"")
    |> Enum.reject(fn(x) -> x == "" end) # reject blank string in array
    |> Enum.chunk_by(fn(x) -> x end)  # group duplicate chars -> [["A", "A"], ["C", "C"]]
    |> Enum.reduce("", fn(letter_group, acc) -> count_letter_group(letter_group, acc) end) # reduce/3
  end
end

Step 2 – run IEx

The file name of the sample code in Step 1 is rle.exs. So I would type the following to start a session with IEx running:

iex rle.exs

In a phoenix application, I might type iex -S mix to ensure the mix file is run.

Step 3 – Call your method

At the command prompt, I would then type RunLengthEncoder.encode(“HORSE”) as an example. Then I would see the following in my terminal:

iex(1)> RunLengthEncoder.encode("HORSE")
Request to pry #PID at rle.exs:14

      @spec encode(String.t) :: String.t
      def encode(string) do
        require IEx; IEx.pry
        String.split(string,"")
        |> Enum.reject(fn(x) -> x == "" end) # reject blank string in array

Allow? [Yn] Y

Step 4 – respawn

Let’s say you did this to understand the value of “string” and you were now satisfied that “HORSE” was indeed passed in as the value.

You can type respawn and the program will continue executing.

Summary

This is the bare bones functionality I learned regarding debugging Elixir but if you’re coming from Ruby and are used to a tool like pry, I hope you find this to be a godsend like I did.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.