Forum: Ruby class_eval and iterations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2006-03-31 07:21
(Received via mailing list)
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!
unknown (Guest)
on 2006-03-31 07:30
(Received via mailing list)
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
This topic is locked and can not be replied to.