raytracer
Change one field in map from string to integer?
Hello,
Elixir noob here! I’ve started a small project to learn Elixir.
I have a map:
map = %{
id: "100"
}
The id value is a string and it needs to be converted to an integer. However the id value may already be an integer and not need converting.
Therefore I wrote this:
map = if String.valid?(map.id) do
x = String.to_integer(map.id)
Map.put(map, :id, x)
else
map
end
The above code works but looks ugly! Is there a better way?
Most Liked
NobbZ
This will not change map.
To make it actually change the value of map you need to assign the result like this:
map = if (map.id |> is_binary), do: map |> Map.replace!(:id,100)
But we do not have an else branch, so what happens when map.id is not binary? We’ll get nil into map, thats not quite the expectation. So we need to add , else: map to make that work as well.
Also I do not think, that piping gives anything here, in fact after adding the else branch, we get another set of parens that feels placed wrong. Since both involved pipes are single “staged” its more readable (in my opinion) to just apply the function.
NobbZ
You can use a function and use pattern matching/guards to do this task:
def convert_id(%{id: id} = data) when is_binary(id), do: %{data | id: String.to_integer(id)}
def convert_id(%{id: id} = data) when is_integer(id), do: data
Or you can use Map.update!/3 with an anonymous function:
map = Map.update!(map, :id, fn
id when is_binary(id) -> String.to_integer(id)
id when is_integer(id) -> id
end)
Both approaches are untested and build in a way that they will crash when id is not parsable into an integer or already is an integer. Also both will crash when there is no key :id in the map.
But why does this happen at all? A much better approach were to build the system in a way that the id is always an integer.
digoio
Yeah, I’m a noob also and just punched that into iex. OK, how’s this?
map = case (map.id |> is_binary) do
true -> Map.replace!(map,:id,100)
false -> map
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








