jihantoro

jihantoro

If inside anonymous function

so i have a code :

whitelisted_params =
  params
  |> Map.take(
    ~w(id ph_id name address)
  )
  |> Enum.map(fn {k, v} -> {String.to_atom(k), String.replace(v, ~r/[^\w\s\-]/, "")} end)

i’m trying to convert String.replace(v, ~r/[^\w\s\-]/, "") to integer if key is id or ph_id

Marked As Solved

NobbZ

NobbZ

The if/2 would work as everywhere else as well:

fn {k, v} ->
  k = String.to_atom(k)
  v = String.replace(v, ~r/[^\w\s\-]/, "")}

  v = if k in [:id, :ph_id] do
    String.to_integer(v)
  else
    v
  end

  {k, v}
end

For a bit more readability I’d also make the chain longer and use pattern matching, like this:

params
|> Map.take(~w(id ph_id name address))
|> Enum.map(fn {k, v} -> {String.to_atom(k), String.replace(v, ~r/[^\w\s\-]/, "")} end)
|> Enum.map(fn
  {k, v} when k in [:id, :ph_id] ->
    {k, String.to_integer(v)}

  tuple ->
    tuple
end)

Where Next?

Popular in Questions Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
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

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54260 488
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 55125 245
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

We're in Beta

About us Mission Statement