Search code examples
dictionaryelixirelixir-iex

Retrieving values from a Map from an Elixir script


If I write a simple Map in Elixir, for example:

person = %{ :name => "Bob", :age => 45}

and I save it as a script, for example

script.exs

How do I retrieve Bob's age after I compile the script with

elixir script.exs ?

Or, even better:

iex script.exs

If I then write person[:age]

It gives me an error:

** (CompileError) iex:1: undefined function person/0

Isn't it possible to use Maps like this in Elixir?


Solution

  • It's a bit hacky, but you can pass the script using the iex --dot-iex script.exs. See The .iex.exs file.

    $ iex --dot-iex script.exs
    Erlang/OTP 21 [erts-10.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]
    
    Interactive Elixir (1.9.1) - press Ctrl+C to exit (type h() ENTER for help)
    iex(1)> person
    %{age: 45, name: "Bob"}
    

    How do I retrieve Bob's age after I compile the script with elixir script.exs?

    Not sure what you mean here. After you run the script, the script has finished, so there's no way to retrieve any of the values (unless the script returns or sets the environment).