I have a keyword list: [key1: "value", key2: "value2", key3: "value3"]
I want to convert it into a string: "key1:value1&key2:value2&key3:value3"
I was thinking to use Enum.reduce, but what will be the arguments to the function?
Since you want to add a separator between the values after mapping them, I'd suggest using Enum.map_join/3
:
iex(1)> list = [key1: "value", key2: "value2", key3: "value3"]
[key1: "value", key2: "value2", key3: "value3"]
iex(2)> list |> Enum.map_join("&", fn {k, v} -> "#{k}:#{v}" end)
"key1:value&key2:value2&key3:value3"
This is how you can do it with Enum.reduce/3
(There's an extra &
inserted at the start which is being removed using String.trim_leading/1
):
iex(3)> list |> Enum.reduce("", fn {k, v}, acc -> "#{acc}&#{k}:#{v}" end) |> String.trim_leading("&")
"key1:value&key2:value2&key3:value3"