NoDisplayName
NoDisplayName

Reputation: 15746

Is there something similar to ruby send method in Elixir?

So I wonder if I can do something similar to this in Elixir?

def some_method(some_param) # a symbol for example
  send(some_param)
end

Upvotes: 7

Views: 942

Answers (1)

Raj
Raj

Reputation: 22956

You can use Kernel.apply/3.

apply(Enum, :reverse, [[1, 2, 3]])

An example:

With a module like this:

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

I can invoke a specific function using it's name:

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

Upvotes: 12

Related Questions