Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir pattern matching maps

Tags:

elixir

I am trying to pattern match a key value in a map and discard everything else.

identity = RedditOAuth2.get_identity(access_token)
# here is how i am getting the key "name" right now.
name = Map.get(identity, "name")
#----------------------------------------
# How would i do something like this
%{"name" => name | rest} = RedditOAuth2.get_identity(access_token)
like image 209
Manos Koutselakis Avatar asked Mar 04 '23 17:03

Manos Koutselakis


2 Answers

You have have multiple = in a single match.

%{"name" => name} = identity = RedditOAuth2.get_identity(access_token)

identity will have the entire map assigned to it and name will have whatever was in the "name" key.

like image 98
Justin Wood Avatar answered Mar 17 '23 05:03

Justin Wood


If you're wanting to discard everything else from the identity and are okay adding another function, you may be looking for Map.split/2.

{%{"name" => name}, identity} =
  access_token
  |> RedditOAuth2.get_identity()
  |> Map.split(["name"])
like image 44
Brett Beatty Avatar answered Mar 17 '23 05:03

Brett Beatty