Splitting a string and get all the values from the map


i was splitting a string that contains all the keys from a map structure and did a Enum.each to get all the values from the map with map.get after that i joined with Enum.join(",")

values_example = String.split(names,",")
                      |> Enum.each(fn(x) -> Map.get(claims,x) end)
                      |> Enum.join(",")

Is it the best way to archive this goal?

Enum.each wont do it. What you want is Enum.map, take a look at the docs:

Hi cevado

i was taking your recomendation but, i have a question i change Enum.each for Enum.map and it work, but in the Map.get it returns nil, i don’t know why but i think that is for String.split.

It depends on how your map is structured, the keys are atoms or strings? Just read the Map.get documentation to understand it’s behavior.

Using your example here:

claims = %{"first" => "First claim", "second" => "Second claim"}
names = "first,second"

|> Enum.map(fn(x) -> Map.get(claims,x) end)
|> Enum.join(",")

Output: "First claim,Second claim"

This will only work if the keys in claims are strings, as you mentioned earlier. If the keys were not strings but instead were atoms, then you would need convert them, probably doing something like:

keys = for name <- String.split(names,","), do: String.to_atom(name)

(I’m going to assume that they’re strings.)

However, I think this way is cleaner:

keys = names |> String.split(",")
claims |> Map.take(keys) |> Map.values |> Enum.join(",")

Output: "First claim,Second claim"