1

How would you take a list of strings, eg.

["jeff", "bezos", "21"]

and map that to a struct

%{:fistname => "jeff", :lastname => "bezos", :age => "21"}

Is it possible to use the Enum functions or would you use the map functions. I need this struct in the specified format so that I can then send it to a database

2 Answers 2

4

I assume the strings are in the same order every time?

Then you can just pattern match:

[firstname, lastname, age] = array
%{:fistname => firstname, :lastname => lastname, :age => age}

If the list contains more than 3 elements:

[firstname, lastname, age | _] = array
%{:fistname => firstname, :lastname => lastname, :age => age}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks very much. So all the data comnes from a csv file, but I only need the first 5 for one struct and then the rest go into another struct would this work say if I did option 2, took the first 3 then did a similar thing but took the 7 after the first 3? or would it have to be done another way?
maybe something like {,,_, other_fields...} = array
well you can do [firstname, lastname, age | rest] = array
all the additional fields will be in rest which is also a list
O right and then you call rest and do the same thing again??
4

You can zip the list of keys with your list of values and then pass that to Map.new/1:

iex(1)> Enum.zip([:firstname, :lastname, :age], ["jeff", "bezos", "21"]) |> Map.new
%{age: "21", firstname: "jeff", lastname: "bezos"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.