Reputation: 7652
I know in Elixir I can initiate a module with a random variable like so:
defmodule MyMod do
@word = "test"
end
but is it possible to initiate this module with a random word something like
defmodule MyMod do
@words = ["test", "hello", "bye"]
@word = @words[1]
end
or even more random than that and have a function that gets called on initialisation that and does some better random logic to determine the starting word?
Upvotes: 1
Views: 293
Reputation: 9568
I wanted to clarify the earlier comment in an answer: yes, you can use Enum.random/1
e.g.
defmodule MyMod do
@words ["test", "hello", "bye"]
@word Enum.random(@words)
end
or you could reference an existing function (e.g. one providing more complex logic). In that case, the function will need to be dynamic, perhaps like:
defmodule MyMod do
f = fn ->
# do something
end
@foo f.()
# ...
end
OR the called function must be isolated in a different module (because you can't make calls to functions/modules that have not yet been compiled).
In one recent example, I used compile-time functions to build out module data from a CSV file.
In either case, you should understand that the evaluation of this code will occur when the module is compiled, not when the code is actually run. This may or may not be what you're looking for: it is not the same as code that gets executed when an instance of an object or class is initialized in the object-oriented paradigm.
Sidenote: the module attributes in elixir are assigned without the equal sign:
- @foo = :bar
+ @foo :bar
Upvotes: 5