How to use a variable as a dynamic key?

Hello, everyone, how to use a variable as a dynamic key?

there’s a scheme:

meetup = 
%RandomCoffee.Events.Meetup{
  __meta__: #Ecto.Schema.Metadata<:built, "meetups">,
  id: 19,
  meetupere1: 1,
  meetupere2: 2,
}

meetup.id -> id

how can a dynamic key be used to obtain values? This option does not work:

variable = "id"
meetup<>".id"

1 Like
iex> meetup = %{id: 1}
%{id: 1}
iex> var = :id
iex> meetup[var]
1

Please remember that transforming string to atom dynamically would not be a good practice.

Oh… this will work for map, but not struct. In that case Map.get should be used.

iex> Map.get meetup, var
1
3 Likes

if use it with the schema, I get an error:

meetup = 
%RandomCoffee.Events.Meetup{
  __meta__: #Ecto.Schema.Metadata<:built, "meetups">,
  id: 19,
  meetupere1: 1,
  meetupere2: 2,
}
var = :id
meetup[var]

UndefinedFunctionError) function RandomCoffee.Events.Meetup.fetch/2 is undefined (RandomCoffee.Events.Meetup does not implement the Access behaviour)

See my Oh… remark in the previous post :slight_smile:

Thanks)

Please @kokolegorille,

Is it the case when doing:

map[var]

Map.get(struct, var)

I mean are those lines safe?

If You want to be sure of keys, You might use Map.fetch, but I am not sure what You mean by safe :slight_smile:

My comment was about this code in the OP…

variable = "id"

… As the string needs to be converted to atom to match keys

This does not transform string to atom, so it is safe in that sense.

1 Like