Why is it `{{name.id}}` and not `{{name}}` in this macro?

macro define_dummy_methods(names)
  {% for name, index in names %}
    def {{name.id}}
      {{index}}
    end
  {% end %}
end

define_dummy_methods [foo, bar, baz]

foo # => 0
bar # => 1
baz # => 2

In this particular example it doesn’t really matter. However using .id on a macro node that is known to be some sort of identifier (method name, type name, etc) is a good practice. The main reason for doing so is it always ensures the name of the method is an identifier. E.g. if your array was ["foo", "bar"], if you didn’t use .id it would generate like def "foo" which is invalid whereas the .id call makes it properly generates as def foo no matter if the name is a string, symbol, or macroId.

3 Likes

Thank you!

Is there a way to log or print somehow the code generated by a macro (so as to check if it is conform to what one expects) ?

Can use the debug macro method:

macro define_dummy_methods(names)
  {% for name, index in names %}
    def {{name.id}}
      {{index}}
    end
  {% end %}

  {% debug %}
end
1 Like