class_eval and iterations

L

leonardo.pires

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!
 
A

ara.t.howard

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top