mzhang.cn / gmail.com a ˝─rit :
> 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?
> 

You may just avoid class variable @@cv and use class instance variable
instead:

---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<
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 { class <<self; def cv() @cv end; end }
puts Cls.cv
Cls.class_eval { def cv() self.class.cv end }
puts c.cv
---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<

It works because classes in ruby are objects themselves.

-- 
Lionel Thiry

Personal web site: http://users.skynet.be/lthiry/