Hi --

On Fri, 22 Dec 2006, gwtmp01 / mac.com wrote:

> I generally avoid class variables but at the last meeting of the New Haven 
> Ruby Brigade a simple question about them led to a long discussion and irb 
> session that only served to confuse us all more.
>
> I'm hoping someone on the list can shed some light on a couple of issues that 
> were raised:
>
>>> class A
>>> @@avar = 'hello'
>>> end
> => "hello"
>>> A.class_variables
> => ["@@avar"]
>>> A.class_eval { puts @@avar }
> NameError: uninitialized class variable @@avar in Object
>       from (irb):5
>       from (irb):5
>>> class A
>>> puts @@avar
>>> end
> hello
> => nil
>>> class A
>>> def get_avar
>>> @@avar
>>> end
>>> end
> => nil
>>> a = A.new
> => #<A:0x4ba360>
>>> a.get_avar
> => "hello"
>>>   a.instance_eval { puts @@avar }
> NameError: uninitialized class variable @@avar in Object
>       from (irb):16
>       from (irb):16
>>> 
>
>
> It seems like a block evaluated by class_eval should have access to  the 
> class variables. Similarly, it seems like if an instance method  (get_avar in 
> the example) has access to the class variable then the  variable should also 
> be visible via instance_eval.
>
> In both examples above (class_eval and instance_eval) it seems like  the 
> class variable @@avar is being looked up relative to the  top_level object 
> and not relative to the class and instance objects  respectively.
>
>
> What am I missing?

You had me at "I generally avoid class variables" :-)

Here's another one you'll like:

   @@avar = 1
   class A
     @@avar = "hello"
   end
   puts @@avar  # => hello

   A.class_eval { puts @@avar }  # => hello

I love Ruby madly, but (or "therefore"? :-) I would be happy never to
see another class variable again.  The confusingness-to-usefulness
ratio is extremely high.


David

-- 
Q. What's a good holiday present for the serious Rails developer?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
    aka The Ruby book for Rails developers!
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)