I am new to Elixir and have I am trying to print something to STDOUT using IO.puts
. IO.puts
requires chardata. I looked at the Elixir docs and didn't see a way to convert tuples to bitstrings. I know there has to be a way to do this but I haven't found any BIF that do this.
So I want to convert this: {"foo", "bar", "baz"}
to this: "foobarbaz"
.
I am in the process of learning Elixir and Erlang so this is all pretty new to me.
Thanks in advance!
Usually we use tuples to hold a fixed amount of data, known up-front. So if you want to print the contents of a tuple, I would recommend doing:
def print_tuple({ foo, bar, baz }) do
IO.puts foo <> bar <> baz
end
If the tuple you want to print has a dynamic size, it is very likely you want to use a list instead. You can convert the elements of a list to a binary using many functions, for example, Enum.join/2
:
IO.puts Enum.join(list)
If you are absolutely sure you want to print the tuple contents, you can do:
IO.puts Enum.join(Tuple.to_list(tuple))
Keep in mind you can print any Elixir data structure by using IO.inspect/1
.
Enum.join
creates a bitstring composed of the consecutive elements of a list. Convert the tuple to a list first. Using the |>
(pipe) operator may improve readability:
{"foo", "bar", "baz"} |> Tuple.to_list |> Enum.join # "foobarbaz"
You can also specify a delimiter:
{"foo", "bar", "baz"} |> Tuple.to_list |> Enum.join(", ") # "foo, bar, baz"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With