On 11/10/05, mzhang.cn / gmail.com <mzhang.cn / gmail.com> wrote:
> Hi all,
> Please look at the following code
> -----------------------------------------------------------
> class Cls
>  @@cv = 0
>  def initialize
>    @iv = 1
>  end
> end
>
> c=Cls.new
> Cls.class_eval { def iv() @iv end }
> puts c.iv
> Cls.class_eval { def cv() @@cv end }
> puts c.cv
> -------------------------------------------------------------
> When running this code snippet, I got the result:
> $ ruby classvar.rb
> 1
> classvar.rb:11:in `cv': uninitialized class variable @@cv in Object
> (NameError).
>
> Why I can't get the class variable in class_eval?

Class variables (i.e. starting with @@) have wierd scoping.
The @@cv you refer to in your closure is looking for resolution
in the scope of the class in which the closure is defined, in this case
the top level Object class.

The only way I know of to get the effect you want is to use string eval:

  Cls.class_eval "def cv() @@cv end "

Regards,

Sean