Simple question about collection processing

I can’t find anywhere a good example on how to solve the following classic task - call a function on every collection item. For example, how to upcase all the Strings in a List:

input = [“elixir”, “ruby”, “123”, “PHOENIX”]

I tried as follows in iex console and it returned nothing but :ok:

Enum.each(input, fn x -> String.upcase(x) end)
:ok 

What am I missing ? Thank you

Welcome to the forum!
Enum.map/2

iex(1)> input = ["elixir", "ruby", "123", "PHOENIX"]
["elixir", "ruby", "123", "PHOENIX"]
iex(2)> Enum.map(input,&(String.upcase(&1)))
["ELIXIR", "RUBY", "123", "PHOENIX"]
iex(3)>

Enum.each/2 is used for functions with side effects.

2 Likes

Yeah, Enum.map is what you want. Enum.each is only useful for side effects. You could print the upcase version in an Enum.each call, but it won’t return any updated data to you.

Consider the difference between:

Enum.each(input, fn x -> IO.inspect(String.upcase(x)) end)

and a version that returns back to you a new data structure that mapped over your input:

Enum.map(input, fn x -> String.upcase(x) end)
3 Likes

Thank you guys, got it :slight_smile:, I also find the answer at Elixir School

Don’t forget to have a look at the official guides.

3 Likes