0

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?

1
  • Probably not the most fastest solution but you can implement a module with a function that returns the required struct and then just compile that file inside the console using the c function -> c("my_file.ex") and use that function to retrieve the value. Commented Sep 23, 2019 at 15:11

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

9 Comments

I meant to use the Map “interactively”, according to my needs, after Elixir loads it. Thus avoiding using a real database. (With all its pluses and minuses, of course). I hope this is clearer now
It's still pretty unclear what you're asking. If you just want to get Bob's age in IEx, use this solution, then try your person[:age] in IEx (person.age should also work). Or are you saying you want to do something like this in an Elixir project you can use from one of your modules?
Just the 1st case you suggested, but after the script is loaded, person[:age] gave me an error, as I wrote. That’s why I asked the question.
In other words, I’d like to use interactively an already written Map from a script, not having to re-write the Map each time.
That information is in the official docs linked from the second sentence. ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.