在Elixir中有类似于ruby send方法的东西吗?

所以我想知道我是否可以在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
相关文章
相关标签/搜索