# Macro expansion on create method in the for loop create duplicate method?

**URL:** <https://forum.crystal-lang.org/t/macro-expansion-on-create-method-in-the-for-loop-create-duplicate-method/7015>\
**Category:** Help & Support\
**Created:** [July 14, 2024, 4:48pm UTC](https://forum.crystal-lang.org/t/macro-expansion-on-create-method-in-the-for-loop-create-duplicate-method/7015 "2024-07-14T16:48:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zw963](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/zw963/32/1623_2.png) [@zw963](https://forum.crystal-lang.org/u/zw963)\
**Post date:** [July 14, 2024, 4:48pm UTC](https://forum.crystal-lang.org/t/macro-expansion-on-create-method-in-the-for-loop-create-duplicate-method/7015/1 "2024-07-14T16:48:58Z")

</div>

```crystal
# 1.cr

{% for name, index in ["foo", "bar", "baz"] %}
  def {{name.id}}
    {{index}}
  end
  {% debug %}
{% end %}

```

The output of `crystal run 1.cr` is:

```auto
def foo
  0
end
def foo
  0
end

def bar
  1
end
def foo
  0
end

def bar
  1
end

def baz
  2
end

```

As above, the method `foo` has been defined 3 times, method `bar` defined 2 times, method `baz` define 1 times.

The correct(expected) result is each method should only be defined once, right?

```crystal
def foo
  0
end

def bar
  1
end

def baz
  2
end

```

Is it for loop doing something wrong, or `{% debug%}`?

* * *

```auto
 ╰─ $ crystal version
Crystal 1.13.1 [0cef61e51] (2024-07-12)

LLVM: 18.1.8
Default target: x86_64-pc-linux-gnu

```

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [July 14, 2024, 5:17pm UTC](https://forum.crystal-lang.org/t/macro-expansion-on-create-method-in-the-for-loop-create-duplicate-method/7015/2 "2024-07-14T17:17:44Z")

</div>

The `{% debug %}` is evaluating each iteration of the for loop. You probably want to do this instead:

```crystal
{% begin %}
  {% for name, index in ["foo", "bar", "baz"] %}
    def {{name.id}}
      {{index}}
    end
  {% end %}
  {% debug %}
{% end %}

```

So it only prints the final result of the loop.

---

<div class="post-metadata">

**Author:** ![zw963](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/zw963/32/1623_2.png) [@zw963](https://forum.crystal-lang.org/u/zw963)\
**Post date:** [July 14, 2024, 5:56pm UTC](https://forum.crystal-lang.org/t/macro-expansion-on-create-method-in-the-for-loop-create-duplicate-method/7015/3 "2024-07-14T17:56:52Z")

</div>

Thanks for explain. i understood now, this issue caused by the `{% debug %}` be evaluate 3 times, but only the last time is what I want.
