Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something similar to ruby send method in Elixir?

Tags:

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
like image 937
NoDisplayName Avatar asked Aug 16 '15 03:08

NoDisplayName


1 Answers

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
like image 146
Lenin Raj Rajasekaran Avatar answered Sep 21 '22 05:09

Lenin Raj Rajasekaran