Tonći Galić – 26 September 2016
256 words in about 2 minutes

One of the most confusing things for folks starting out with Elixir is when a list of integers gets displayed as characters in IEx console.

Let’s see an example:

1
2
iex(1)> [7,8 ,9 ,10]
'\a\b\t\n'

The reason behind this is mentioned in the FAQ of Elixir. There are different ways to force IEx to display a list of integers:

1 . append a non-ascii printable number, like 0:

1
2
iex(2)> [7,8 ,9 ,10] ++ [0]
[7, 8, 9, 10, 0]

2 . instruct inspect/2 not to treat input list as charlist

1
2
iex(3)> inspect [27, 35, 51], char_lists: false
[27, 35, 51]

However, both can be annoying as you have to think ahead how your input will be shown. There’s a third, less known option:

3 . configure IEx to always use inspect/2 with the above option

1
2
3
4
iex(4)> IEx.configure inspect: [char_lists: false]
:ok
iex(5)> [7,8, 9,10]
[7, 8, 9, 10]

If you’re starting out, you might want to add that to your ~/.iex.exs (which is run every time you start IEx). You can also undo that behaviour:

1
2
3
4
iex(6)> IEx.configure inspect: [char_lists: :as_char_lists]
:ok
iex(7)> [7,8 ,9 ,10]
'\a\b\t\n'

BTW, Kernel.inspect/2 has more nice features, like showing number in a different representation (binary, hex or octal). You’ll find most mentioned in the docs (from console: h Kernel.inspect or online ):

1
2
3
4
5
6
iex(8)> inspect(100, base: :binary)
"0b1100100"
iex(9)> inspect(100, base: :hex)
"0x64"
iex(10)> inspect(100, base: :octal)
"0o144"

Feel free to share any tips/tricks you know in the comments below :D

Tonći Galić

Polyglot Web Developer • GitHub: @Tuxified • Twitter: @Tuxified