所以我想知道我是否可以在Elixir中做类似的事情?
def some_method(some_param) # a symbol for example send(some_param) end
解决方法
你可以使用
Kernel.apply/3.
apply(Enum,:reverse,[[1,2,3]])
一个例子:
使用这样的模块:
defmodule Apply do def dynamic(method_name,params) do apply(Apply,method_name,params) end def method1(params) do IO.puts "Method 1,called by " <> params end def method2(params) do IO.puts "Method 2,called by " <> params end end
iex(1)> c("apply.ex") [Apply] iex(2)> Apply.dynamic(:method1,["Hey"]) Method 1,called by Hey :ok iex(3)> Apply.dynamic(:method2,["Hey"]) Method 2,called by Hey :ok