elixirets

String Manipulation: join with comma


How can I get below string as result from the way i am getting it right now in elixir.

['x1', 'x2']

I tried with enum.join but did not get the desired data

to

'x1,x2'

Solution

  • If I understand correctly, you should use Enum.join/2 with the second parameter to define the "joiner". this should work:

    arr = ['x1', 'x2']
    Enum.join(arr, ",")
    # => "x1,x2"
    

    If you want the result to be char list, you can turn it to one using String.to_char_list/1:

    String.to_char_list(Enum.join(arr, ","))
    # => 'x1,x2'
    

    Another option is to use Enum.reduce/2 and add the joiner explicitly:

    Enum.reduce(arr, &(&2 ++ ',' ++ &1))               
    # => 'x1,x2'