Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IO.puts vs IO.inspect

Tags:

elixir

It seems to me that IO.puts and IO.inspect are both used to print to the console. What is the difference between them?

like image 622
koolkat Avatar asked Jun 20 '17 22:06

koolkat


Video Answer


2 Answers

Adding to the previous answer, IO.inspect can print an arbitrary elixir term, with an optional keyword list containing a label: and values for initializing an Inspect.Opts struct:

@spec inspect(item, Keyword.t) :: item when item: var

IO.puts requires the argument to be either a string, or a struct that implements the String.Chars protocol:

@spec puts(device, chardata | String.Chars.t) :: :ok
like image 178
Mike Buhot Avatar answered Oct 19 '22 10:10

Mike Buhot


Reading through the Elixir docs, it looks like IO.puts/2 is simply going to write and append a newline.

IO.inspect/2 will do the same thing, but it also returns the first value unchanged (so it's chainable), enables pretty printing/decoration and other formatting options.

  • https://hexdocs.pm/elixir/IO.html#inspect/2
  • https://hexdocs.pm/elixir/IO.html#print/2

Friendly reminder that hexdocs can be really awesome. I was able to easily find the answer to your question and learn the differences myself. I highly encourage you to read through modules you normally use to discover other functions you might not know about that you could be benefitting from.

like image 35
Tyler Willingham Avatar answered Oct 19 '22 09:10

Tyler Willingham