# Class\_eval and iterations

**URL:** <https://www.ruby-forum.com/t/class-eval-and-iterations/56428>\
**Category:** Ruby\
**Created:** [March 31, 2006, 5:21am UTC](https://www.ruby-forum.com/t/class-eval-and-iterations/56428 "2006-03-31T05:21:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 31, 2006, 5:21am UTC](https://www.ruby-forum.com/t/class-eval-and-iterations/56428/1 "2006-03-31T05:21:06Z")

</div>

Hello,

I’m trying to write a code similar to the below:

class Module  
def foo(\*names)  
for name in names  
class\_eval do  
define\_method(name) do  
puts name  
end  
end  
end  
end  
end

class Goo  
foo :a, :b, :c  
end

I was expecting to

bar = Goo.new

bar.a prints ‘a’, bar.b prints ‘b’, and bar.c prints ‘c’. But all  
methods prints ‘c’. Why?

Thanks!

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 31, 2006, 5:30am UTC](https://www.ruby-forum.com/t/class-eval-and-iterations/56428/2 "2006-03-31T05:30:09Z")

</div>

On Fri, 31 Mar 2006, removed\_email\_address@domain.invalid wrote:

> ```
> end
> 
> ```
> 
> I was expecting to
> 
> bar = Goo.new
> 
> bar.a prints ‘a’, bar.b prints ‘b’, and bar.c prints ‘c’. But all  
> methods prints ‘c’. Why?
> 
> Thanks!

```
 harp:~ > cat a.rb
 class Module
   def foo(*names)
     names.each do |name|
       class_eval{ define_method(name){ name } }
     end
   end
 end

 class Goo
   foo :a, :b, :c
 end

 goo = Goo.new
 p goo.a
 p goo.b
 p goo.c

 harp:~ > ruby a.rb
 :a
 :b
 :c

```

it has to do with the difference between ‘for’ and ‘each’ - search the  
archives  
for ‘decoux for each’.

basically your method block was bound to a non-block local variable that  
was  
cycled a-\>b-\>c - finally existing as c. with ‘each’ you get a block  
local

moral. never use ‘for’

hth.

-a
