I’d like to know what exactly a method name is in elixir:
array = [1,2,3]
module_name = :lists
method_name = :nth # this not working
module_name.method_name(1, array) # error, undef function lists.method_name/2
module_name.nth(1, array) # returns 1, module_name is OK. It's an atom
But I can do almost the same thing in erlang:
A = [1,2,3].
X = lists.
Y = nth.
X:Y(1,A). # returns 1
How can I do this in elixir?
You can use
apply/3which is just a wrapper around:erlang.apply/3. It simply invokes the givenfunctionfrom themodulewith an array ofarguments. Since you are passing arguments as the module and function names you can use variables.If you want to understand more about how elixir handles function calls (and everything else) you should take a look at
quoteandunquote.which returns the homoiconic representation of the function call.
You can
unquotethe quoted function call withCode.eval_quoted/3Edit: here is an example using Enum.fetch along with a var.