简体   繁体   中英

Elixir: Printing list along with string

I would like to print a list along with a string identifier like

list = [1, 2, 3]
IO.puts "list is ", list

This does not work. I have tried few variations like

# this prints only the list, not any strings
IO.inspect list
# using puts which also does not work
IO.puts "list is #{list}" 

In javascript, I could simply do console.log("list is ", list) . I'm confused how I could achieve the same in elixir.

Starting with Elixir 1.4, IO.inspect/2 accepts label option among others :

IO.inspect list, label: "The list is"
#⇒ The list is: [1, 2, 3]

Maybe there's a better way (I'm new to Elixir too) but this worked for me:

IO.puts(["list is ", Enum.join(list, " ")])                             
list is 1 2 3

Interpolation works too:

IO.puts("list is #{Enum.join(list, " ")}")

Edit: inspect seems to better than Enum.join for this use case:

IO.puts("list is #{inspect(list)}")
list is [1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM