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
Enum.each(input, fn x -> String.upcase(x) end)
What am I missing ? Thank you
Welcome to the forum!
iex(1)> input = ["elixir", "ruby", "123", "PHOENIX"]
["elixir", "ruby", "123", "PHOENIX"]
["ELIXIR", "RUBY", "123", "PHOENIX"]
Enum.each/2 is used for functions with side effects.
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)
Thank you guys, got it , I also find the answer at Elixir School
Don’t forget to have a look at the official guides.