achedeuzot
achedeuzot

Reputation: 4384

Map.get cannot retrieve value with string keys

I'm having a strange issue with Maps. Here's a small example to reproduce the behaviour:

defmodule Document do

  @expiration_presets_to_timeshift %{
    "immediately": [seconds: 1],
    "1-minute": [minutes: 1],
    "1-hour": [hours: 1],
    "1-day": [days: 1],
    "1-week": [weeks: 1],
    "1-month": [months: 1],
    "1-year": [years: 1],
    "never": [years: 9999],
  }

  def expiration_presets, do: @expiration_presets_to_timeshift
end

If we then try to retrieve information from the map:

iex(1)> import Document
Document
iex(2)> Document.expiration_presets
%{"1-day": [days: 1], "1-hour": [hours: 1], "1-minute": [minutes: 1],
"1-month": [months: 1], "1-week": [weeks: 1], "1-year": [years: 1],
immediately: [seconds: 1], never: [years: 9999]}
iex(3)> Document.expiration_presets["1-hour"]
nil
iex(4)> Map.get(Document.expiration_presets, "1-hour")
nil

I notice two strange behaviors:

  1. The "immediately" and "never" keys have become atoms. I never asked for this. Why ?
  2. I can't seem to retrieve the value using the key strings (Map.get/2 and Map.[key] both return nil). Why is that and how can I retrieve the value out of the map ?

Upvotes: 0

Views: 490

Answers (1)

christopheradams
christopheradams

Reputation: 36

The map syntax for string keys looks like:

%{"immediately" => [seconds: 1]}

Update your map to use that style first.

Also the function is missing a :

def expiration_presets, do: @expiration_presets_to_timeshift

Upvotes: 2

Related Questions