On Oct 8, 2007, at 9:16 AM, Dave Baldwin wrote:

> I want to use class variables and have them accessible from class  
> methods that have been defined outside of the class using  
> define_method or something similar.  When I try this the class  
> variable isn't in scope.  A simple test case is:
>
> class A
> 	@@aa = 20
> end
>
> A.class_eval {define_method(:foo){puts @aa}}
>
> a = A.new
> a.foo			=> nil and not 20 as expected
>
> or using
>
> A.send(:define_method, :foo){puts @aa}
> a.foo			=> nil and not 20 as expected
>
> gives the same result but
>
> class A
> 	def foo
> 		puts @@aa
> 	end
> end
>
> a.foo			=> 20 as expected.
>
> How do I get the same behaviour as opening the class and defining  
> the method normally?
>
> Thanks,
>
> Dave.


cfp:~ > cat a.rb
class A; @@aa = 42;end

A.class_eval{ define_method(:foo){ A.send :class_variable_get,  
'@@aa' } }
p A.new.foo #=> 42

A.send(:define_method, :foo){ A.send :class_variable_get, '@@aa' }
p A.new.foo #=> 42

@@aa = 'this is what is meant by closure'

A.send(:define_method, :foo){ @@aa }
p A.new.foo #=> ??


cfp:~ > ruby a.rb
42
42
"this is what is meant by closure"


blocks form closures, which is what makes them useful, when you are  
defining methods via blocks you need to consider the enclosing scope  
as it will be the *primary* namespace lookup.  understanding closures  
is step one to metaprogramming bliss.

kind regards.

a @ http://codeforpeople.com/
--
share your knowledge.  it's a way to achieve immortality.
h.h. the 14th dalai lama