Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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"

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)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top