On Fri, 31 Mar 2006, leonardo.pires / gmail.com wrote: > 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! 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 -- share your knowledge. it's a way to achieve immortality. - h.h. the 14th dali lama