How to create a dynamic function name using Elixir macro?

To achieve this, you can prepend :add_ to the name before unquoting. Also, the parentheses after the method name in this case are required to prevent ambiguities. This should do the trick:

defmacro generate_dynamic(name) do
  quote do 
    def unquote(:"add_#{name}")() do
      # ...
    end
  end
end

Sometimes, as a useful shortcut, you can achieve the same result inline, without writing a macro using an unquote fragment.

defmodule Hello do
  [:alice, :bob] |> Enum.each fn name ->
    def unquote(:"hello_#{name}")() do
      IO.inspect("Hello #{unquote(name)}")
    end
  end
end

Hello.hello_bob    # => "Hello bob"
Hello.hello_alice  # => "Hello alice"

Tags:

Elixir