raytracer

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

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

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

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

Where Next?

Popular in Questions Top

New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement