17

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!

3 Answers 3

33

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.

1
  • 3
    Since Elixir v0.13.3 it's Enum.join(Tuple.to_list(tuple)).
    – ciastek
    Feb 15, 2016 at 16:36
14

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"
1
  • 9
    Please explain your answer Feb 3, 2014 at 23:28
1

This should do the job:

def concat_binaries(binaries) do
    List.foldr(binaries, <<>>, fn(a, b) -> <<a :: binary, b :: binary>> end)
end

tuple = {"foo", "bar", "baz"}
IO.puts(concat_binaries(tuple_to_list(tuple)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.