script
March 14, 2018, 6:46am
1
I want to update the map with multiple values. This is the code:
@intergers [:approved_by, :deleted_by, :id, :inserted_by, :user_id, :updated_by]
Enum.map(@intergers, fn(x) -> Map.put(map, x, Enum.random(1..10))end)
This gives me the output with updating the value in each iteration not the whole map so at
end I have only the last key :updated_by
is changed while the rest of the map stays the same.
How can I update the map for all these keys
Thanks!
idi527
March 14, 2018, 6:55am
2
You can use a reduce function.
Enum.reduce(@intergers, map, fn x, acc ->
Map.put(acc, x, Enum.random(1..10))
end)
Enum.random(1..10)
can be replaced by a bit more efficient :rand.uniform(10)
.
iex(6)> :timer.tc fn -> Enum.each(1..1000, fn _ -> Enum.random(1..10) end) end
{9304, :ok} # 9.3 ms
iex(7)> :timer.tc fn -> Enum.each(1..1000, fn _ -> :rand.uniform(10) end) end
{1443, :ok} # 1.4 ms
script
March 14, 2018, 7:04am
3
Thanks. I will definitely consider this.